diff --git a/Makefile b/Makefile index cd81971..6923615 100644 --- a/Makefile +++ b/Makefile @@ -22,7 +22,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/openai.o src/transport_openai.o src/builtin.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/plugin.o BIN = splinter BINOBJ = src/main.o src/ui.o @@ -30,7 +30,7 @@ PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \ plugins/cli/cli.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_cli tests/test_compactor + tests/test_theme tests/test_plugin tests/test_sse tests/test_cli tests/test_compactor RPATH = -Wl,-rpath,'$$ORIGIN' PLUGIN_RPATH = -Wl,-rpath,'$$ORIGIN/../..' @@ -81,6 +81,7 @@ src/session.o: include/splinter.h src/transport.o: include/splinter.h src/conv.o: include/splinter.h src/json.o: vendor/libmcp/mcp.h +src/sse.o: include/splinter.h vendor/libmcp/mcp.h src/openai.o: include/splinter.h vendor/libmcp/mcp.h src/transport_openai.o: include/splinter.h src/builtin.o: include/splinter.h @@ -106,6 +107,8 @@ tests/test_openai: tests/test_openai.c $(LIB) $(CC) $(CFLAGS) -o $@ tests/test_openai.c -L. -lsplinter $(TEST_RPATH) $(LIBS) tests/test_theme: tests/test_theme.c $(LIB) $(CC) $(CFLAGS) -o $@ tests/test_theme.c -L. -lsplinter $(TEST_RPATH) $(LIBS) +tests/test_sse: tests/test_sse.c $(LIB) + $(CC) $(CFLAGS) -o $@ tests/test_sse.c -L. -lsplinter $(TEST_RPATH) $(LIBS) tests/test_cli: tests/test_cli.c $(LIB) $(PLUGIN) $(CC) $(CFLAGS) -o $@ tests/test_cli.c -L. -lsplinter $(TEST_RPATH) $(LIBS) diff --git a/README.md b/README.md index c3a4a8a..9b12a1f 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,26 @@ The `cli` transport runs a program and takes its stdout as the answer, so `claude -p`, `opencode run`, `ollama run` or a script can be the brains. The OpenAI adapter stays the default for local endpoints. +## Streaming + +Answers arrive as they are produced, not as one block: the adapter reads SSE, +turns text deltas into the chat pane and tool-call starts into the sidebar, and +a reasoning model's own `reasoning_content` is shown dimmed one line above the +answer instead of being hidden. In one-shot mode the text goes straight to +stdout as it comes. + +Both directions are covered by `test_sse`, which feeds recorded lines: plain +text, a tool call split across three chunks, two calls in one turn, a broken +data line, and the keepalive lines that carry nothing. + +## Screen encoding, measured + +The vendored NetBSD curses emits Latin-1 bytes for wide characters (`ü` becomes +`0xFC`); ncurses passes UTF-8 through. So the UI transliterates for display +(`gruen`), while the conversation and the session log keep the exact UTF-8. +That is a defect in the ported library, recorded here instead of being papered +over with a claim that it works. + ## Steering while a turn runs The turn runs on its own thread, so the keyboard stays live. While it runs, the diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md index 76ed0f4..ad2437b 100644 --- a/docs/PLUGINS.md +++ b/docs/PLUGINS.md @@ -33,6 +33,10 @@ working. | `tick()` | its own | yes | no | | `draw()` | main (UI) | no | no | +Streaming is a transport concern, not a plugin one: `sp_transport.send_stream` +is optional, and a transport that cannot stream leaves it NULL — the loop then +falls back to the one-shot call. + `tick()` runs on a thread the host creates and can stop. It may read files, wait on sockets, sleep. It must not assume it is the only thread. diff --git a/include/splinter.h b/include/splinter.h index 9ae66b3..293d92b 100644 --- a/include/splinter.h +++ b/include/splinter.h @@ -123,9 +123,25 @@ struct sp_reply { * seam is the conversation, not a raw string: a provider adapter cannot invent * history, and the loop cannot depend on a vendor's JSON. */ +/* + * Streaming: a transport that can deliver a turn incrementally reports text + * deltas and tool-call starts through this callback while it reads. A transport + * that cannot simply leaves send_stream NULL and the loop uses send(). + */ +enum { + SP_STREAM_TEXT = 1, /* a chunk of the assistant's answer */ + SP_STREAM_TOOL, /* a tool call has begun: text is its name */ + SP_STREAM_THINK /* the model is reasoning: show it, do not use it */ +}; + +typedef void (*sp_stream_cb)(void *ctx, int kind, const char *text); + struct sp_transport { int (*send)(void *ctx, const struct sp_conv *, struct sp_reply *out, struct sp_buf *err); + int (*send_stream)(void *ctx, const struct sp_conv *, + struct sp_reply *out, struct sp_buf *err, + sp_stream_cb, void *cbctx); void *ctx; }; @@ -179,6 +195,10 @@ struct sp_agent_config { volatile int *cancel; int (*steer)(void *ctx, struct sp_buf *out); void *steer_ctx; + + /* incremental output, if the transport and the caller both support it */ + sp_stream_cb stream; + void *stream_ctx; }; struct sp_agent_stats { @@ -213,8 +233,22 @@ struct sp_transport sp_openai_transport(const char *url, const char *model, /* openai.c -- pure JSON shaping, testable without a network */ int sp_openai_request(const struct sp_conv *, const char *model, - const struct sp_registry *, struct sp_buf *out); + const struct sp_registry *, int streaming, struct sp_buf *out); int sp_openai_reply(const char *json, struct sp_reply *out, struct sp_buf *err); +/* SSE accumulation, one line at a time, so it can be tested without a socket */ +struct sp_sse; +struct sp_sse *sp_sse_new(void); +void sp_sse_free(struct sp_sse *); +/* Feed one line (with or without its newline). Returns 1 when a delta was + * produced (written to out, may be empty), 0 for lines that carry nothing, + * -1 on a parse error with the line quoted. */ +int sp_sse_line(struct sp_sse *, const char *line, struct sp_buf *out, + struct sp_buf *err); +/* Turn the accumulated state into a reply. Returns 0 or -1. */ +int sp_sse_finish(struct sp_sse *, struct sp_reply *out, struct sp_buf *err); +int sp_sse_done(const struct sp_sse *); +const char *sp_sse_tool_start(const struct sp_sse *, size_t index); + #endif /* SPLINTER_H */ diff --git a/libsplinter.so b/libsplinter.so index 8003bdc..7b2a067 100755 Binary files a/libsplinter.so and b/libsplinter.so differ diff --git a/plugins/cli/cli.so b/plugins/cli/cli.so index dc2a4c9..4a7e16b 100755 Binary files a/plugins/cli/cli.so and b/plugins/cli/cli.so differ diff --git a/src/agent.c b/src/agent.c index c8a30bf..f10244b 100644 --- a/src/agent.c +++ b/src/agent.c @@ -140,9 +140,21 @@ sp_agent_run(struct sp_agent *a, const char *user_text, struct sp_buf *answer, a->stats.bytes_sent += sent; a->stats.steps++; - if (a->tr.send(a->tr.ctx, conv, &reply, err) != 0) { - sp_reply_free(&reply); - goto out; + { + int sent_rc; + + if (a->cfg->stream != NULL && + a->tr.send_stream != NULL) + sent_rc = a->tr.send_stream(a->tr.ctx, conv, + &reply, err, a->cfg->stream, + a->cfg->stream_ctx); + else + sent_rc = a->tr.send(a->tr.ctx, conv, &reply, + err); + if (sent_rc != 0) { + sp_reply_free(&reply); + goto out; + } } if (reply.status < 200 || reply.status > 299) { sp_buf_printf(err, "agent: transport status %ld", diff --git a/src/main.c b/src/main.c index c2b3fec..6cb97aa 100644 --- a/src/main.c +++ b/src/main.c @@ -87,6 +87,17 @@ load_script(struct sp_mock *m, const char *path, struct sp_buf *err) return 0; } +/* one-shot mode: print the answer as it arrives, no buffering */ +static void +stdout_stream(void *ctx, int kind, const char *text) +{ + (void)ctx; + if (kind != SP_STREAM_TEXT || text == NULL) + return; + fputs(text, stdout); + fflush(stdout); +} + int main(int argc, char **argv) { @@ -330,9 +341,12 @@ main(int argc, char **argv) return rc; } + cfg.stream = stdout_stream; + cfg.stream_ctx = NULL; rc = sp_agent_run(&ag, prompt, &answer, &err); if (rc == 0) { - printf("%s\n", answer.p); + /* streamed output already reached the terminal; just end the line */ + printf("\n"); } else { fprintf(stderr, "splinter: %s\n", err.p ? err.p : "turn failed"); } diff --git a/src/openai.c b/src/openai.c index 8ec5c9a..477bd0c 100644 --- a/src/openai.c +++ b/src/openai.c @@ -34,14 +34,15 @@ put_field(struct sp_buf *b, const char *key, const char *value) int sp_openai_request(const struct sp_conv *conv, const char *model, - const struct sp_registry *reg, struct sp_buf *out) + const struct sp_registry *reg, int streaming, struct sp_buf *out) { size_t i; sp_buf_clear(out); if (sp_buf_puts(out, "{\"model\":") != 0 || sp_buf_puts(out, "\"") != 0 || sp_json_escape(out, model != NULL ? model : "") != 0 || - sp_buf_puts(out, "\",\"stream\":false,\"messages\":[") != 0) + sp_buf_puts(out, streaming ? "\",\"stream\":true,\"messages\":[" + : "\",\"stream\":false,\"messages\":[") != 0) return -1; for (i = 0; i < conv->n; i++) { diff --git a/src/sse.c b/src/sse.c new file mode 100644 index 0000000..af5593a --- /dev/null +++ b/src/sse.c @@ -0,0 +1,296 @@ +/* + * splinter -- SSE accumulation for streaming chat completions. + * + * Copyright (c) 2026 Konrad Lother + * SPDX-License-Identifier: BSD-3-Clause + * + * OpenAI streams a turn as `data: {json}` lines. Text arrives in + * `choices[0].delta.content` chunks; a tool call arrives in pieces: the name + * once, the arguments as a growing string, keyed by an index. This file turns + * that into one reply, and it does it one line at a time so the whole thing is + * testable with recorded lines and no socket. + * + * Anything it does not understand is reported with the line quoted. A silent + * skip here would mean a turn that ends with no answer and no reason. + */ +#include +#include +#include + +#include "splinter.h" +#include "mcp.h" + +#define MAX_CALLS 8 + +struct sse_call { + char *id; + char *name; + struct sp_buf args; + int seen; +}; + +struct sp_sse { + struct sp_buf content; + struct sp_buf think; + struct sse_call calls[MAX_CALLS]; + size_t ncalls; + int done; +}; + +struct sp_sse * +sp_sse_new(void) +{ + struct sp_sse *s = calloc(1, sizeof(*s)); + + if (s == NULL) + return NULL; + if (sp_buf_init(&s->content) != 0 || sp_buf_init(&s->think) != 0) { + free(s); + return NULL; + } + return s; +} + +void +sp_sse_free(struct sp_sse *s) +{ + size_t i; + + if (s == NULL) + return; + for (i = 0; i < s->ncalls; i++) { + free(s->calls[i].id); + free(s->calls[i].name); + sp_buf_free(&s->calls[i].args); + } + sp_buf_free(&s->content); + sp_buf_free(&s->think); + free(s); +} + +int +sp_sse_done(const struct sp_sse *s) +{ + return s != NULL ? s->done : 0; +} + +const char * +sp_sse_tool_start(const struct sp_sse *s, size_t index) +{ + if (s == NULL || index >= s->ncalls) + return NULL; + return s->calls[index].name; +} + +static struct sse_call * +call_slot(struct sp_sse *s, size_t index) +{ + if (index >= MAX_CALLS) + return NULL; + if (index >= s->ncalls) { + size_t i; + + for (i = s->ncalls; i <= index; i++) { + memset(&s->calls[i], 0, sizeof(s->calls[i])); + if (sp_buf_init(&s->calls[i].args) != 0) + return NULL; + } + s->ncalls = index + 1; + } + return &s->calls[index]; +} + +int +sp_sse_line(struct sp_sse *s, const char *line, struct sp_buf *out, + struct sp_buf *err) +{ + mcp_json *v; + const mcp_json *choices, *choice, *delta, *content, *tcs; + int produced = 0; + const char *payload; + + if (s == NULL) + return -1; + while (*line == ' ' || *line == '\t') + line++; + if (*line == '\0' || *line == ':' || *line == '\n') + return 0; + if (strncmp(line, "data:", 5) != 0) { + /* event:/id:/retry: carry nothing we need */ + return 0; + } + payload = line + 5; + while (*payload == ' ') + payload++; + if (strncmp(payload, "[DONE]", 6) == 0) { + s->done = 1; + return 0; + } + + v = mcp_parse(payload); + if (v == NULL) { + sp_buf_printf(err, "sse: unparseable data line: %.200s", payload); + return -1; + } + + choices = mcp_arg(v, "choices"); + if (choices == NULL || mcp_array_len(choices) == 0) { + /* keepalive and usage-only events land here */ + mcp_json_free(v); + return 0; + } + choice = mcp_array_at(choices, 0); + delta = mcp_arg(choice, "delta"); + if (delta == NULL) { + mcp_json_free(v); + return 0; + } + + content = mcp_arg(delta, "content"); + if (content != NULL && mcp_json_string(content) != NULL) { + const char *text = mcp_json_string(content); + + if (sp_buf_puts(&s->content, text) != 0 || + sp_buf_puts(out, text) != 0) { + mcp_json_free(v); + return -1; + } + produced = 1; + } + + /* reasoning models report their thinking in a separate field */ + { + const mcp_json *think = mcp_arg(delta, "reasoning_content"); + + if (think != NULL && mcp_json_string(think) != NULL) { + if (sp_buf_puts(&s->think, mcp_json_string(think)) != 0 || + sp_buf_puts(out, mcp_json_string(think)) != 0) { + mcp_json_free(v); + return -1; + } + produced = 1; + } + } + + tcs = mcp_arg(delta, "tool_calls"); + if (tcs != NULL) { + size_t i, n = mcp_array_len(tcs); + + for (i = 0; i < n; i++) { + const mcp_json *tc = mcp_array_at(tcs, i); + const mcp_json *fn = mcp_arg(tc, "function"); + const mcp_json *idx = mcp_arg(tc, "index"); + const mcp_json *id = mcp_arg(tc, "id"); + struct sse_call *slot; + int index = (int)mcp_arg_int(tcs, "index", -1); + + if (idx != NULL) + index = (int)mcp_arg_int(delta, "index", index); + /* the index lives on the tool call itself in OpenAI's shape */ + index = (int)mcp_arg_int(tc, "index", index); + if (index < 0) + index = (int)(s->ncalls == 0 ? 0 : s->ncalls - 1); + slot = call_slot(s, (size_t)index); + if (slot == NULL) { + mcp_json_free(v); + sp_buf_puts(err, "sse: too many tool calls"); + return -1; + } + if (id != NULL && mcp_json_string(id) != NULL && + slot->id == NULL) { + slot->id = strdup(mcp_json_string(id)); + slot->seen = 1; + } + if (fn != NULL) { + const mcp_json *name = mcp_arg(fn, "name"); + const mcp_json *args = mcp_arg(fn, "arguments"); + + if (name != NULL && mcp_json_string(name) != NULL && + slot->name == NULL) { + slot->name = + strdup(mcp_json_string(name)); + slot->seen = 1; + if (sp_buf_puts(out, slot->name) != 0) { + mcp_json_free(v); + return -1; + } + produced = 1; + } + if (args != NULL && mcp_json_string(args) != NULL && + sp_buf_puts(&slot->args, + mcp_json_string(args)) != 0) { + mcp_json_free(v); + return -1; + } + } + } + } + + mcp_json_free(v); + return produced; +} + +int +sp_sse_finish(struct sp_sse *s, struct sp_reply *out, struct sp_buf *err) +{ + size_t i; + int any = 0; + + if (s == NULL || out == NULL) + return -1; + out->status = 200; + out->content = strdup(s->content.p != NULL ? s->content.p : ""); + if (out->content == NULL) + return -1; + for (i = 0; i < s->ncalls; i++) + if (s->calls[i].seen) + any = 1; + if (!any) + return 0; + + out->calls = calloc(s->ncalls, sizeof(*out->calls)); + if (out->calls == NULL) + return -1; + out->ncalls = s->ncalls; + for (i = 0; i < s->ncalls; i++) { + out->calls[i].id = strdup(s->calls[i].id != NULL ? + s->calls[i].id : "call-0"); + out->calls[i].name = strdup(s->calls[i].name != NULL ? + s->calls[i].name : ""); + out->calls[i].args = strdup(s->calls[i].args.p != NULL ? + s->calls[i].args.p : "{}"); + if (out->calls[i].id == NULL || out->calls[i].name == NULL || + out->calls[i].args == NULL) { + sp_reply_free(out); + return -1; + } + } + + /* hand the provider's structure back verbatim next round */ + { + struct sp_buf json; + + if (sp_buf_init(&json) != 0) + return -1; + sp_buf_puts(&json, "["); + for (i = 0; i < s->ncalls; i++) { + if (i > 0) + sp_buf_puts(&json, ","); + sp_buf_puts(&json, "{\"id\":\""); + sp_json_escape(&json, out->calls[i].id); + sp_buf_puts(&json, "\",\"type\":\"function\"," + "\"function\":{\"name\":\""); + sp_json_escape(&json, out->calls[i].name); + sp_buf_puts(&json, "\",\"arguments\":\""); + sp_json_escape(&json, out->calls[i].args); + sp_buf_puts(&json, "\"}}"); + } + sp_buf_puts(&json, "]"); + out->calls_json = strdup(json.p); + sp_buf_free(&json); + if (out->calls_json == NULL) + return -1; + } + (void)err; + return 0; +} diff --git a/src/transport_openai.c b/src/transport_openai.c index 8a1247f..fb14156 100644 --- a/src/transport_openai.c +++ b/src/transport_openai.c @@ -63,7 +63,7 @@ openai_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, sp_buf_puts(err, "openai: out of memory"); return -1; } - if (sp_openai_request(conv, c->model, c->reg, &body) != 0) { + if (sp_openai_request(conv, c->model, c->reg, 0, &body) != 0) { sp_buf_puts(err, "openai: cannot build the request"); goto out; } @@ -132,6 +132,126 @@ out: return rc; } +/* + * Streaming: curl stays attached (-N) and its stdout is read line by line. + * Each line goes through the SSE accumulator, which reports text deltas and + * the start of a tool call. When the stream ends without content and without a + * tool call, the collected non-data lines are shown: an endpoint that answers + * with an error page must not look like a model that said nothing. + */ +static int +openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, + struct sp_buf *err, sp_stream_cb cb, void *cbctx) +{ + struct openai_ctx *c = ctx; + struct sp_buf body, cmd, tail, delta; + struct sp_sse *sse; + char path[] = "/tmp/splinter-sse-XXXXXX"; + FILE *p; + int fd, rc = -1; + ssize_t w; + size_t n; + char line[8192]; + int saw_data = 0; + + if (c == NULL) + return -1; + if (sp_buf_init(&body) != 0 || sp_buf_init(&cmd) != 0 || + sp_buf_init(&tail) != 0 || sp_buf_init(&delta) != 0) + return -1; + sse = sp_sse_new(); + if (sse == NULL) { + sp_buf_puts(err, "openai: out of memory"); + return -1; + } + if (sp_openai_request(conv, c->model, c->reg, 1, &body) != 0) { + sp_buf_puts(err, "openai: cannot build the request"); + goto out; + } + + fd = mkstemp(path); + if (fd < 0) { + sp_buf_printf(err, "openai: mkstemp: %s", strerror(errno)); + goto out; + } + n = body.len; + w = write(fd, body.p, n); + close(fd); + if (w < 0 || (size_t)w != n) { + sp_buf_printf(err, "openai: short write: %s", strerror(errno)); + unlink(path); + goto out; + } + + sp_buf_printf(&cmd, "curl -sS -N -m %ld -X POST -H 'Content-Type: " + "application/json'", c->timeout_s); + if (c->key[0] != '\0') + sp_buf_printf(&cmd, " -H 'Authorization: Bearer %s'", c->key); + sp_buf_printf(&cmd, " --data-binary @%s '%s'", path, c->url); + + p = popen(cmd.p, "r"); + if (p == NULL) { + sp_buf_printf(err, "openai: popen: %s", strerror(errno)); + unlink(path); + goto out; + } + while (fgets(line, sizeof(line), p) != NULL) { + int produced; + + if (strncmp(line, "data:", 5) == 0) + saw_data = 1; + else if (tail.len < 4096) + sp_buf_puts(&tail, line); + sp_buf_clear(&delta); + produced = sp_sse_line(sse, line, &delta, err); + if (produced < 0) { + pclose(p); + unlink(path); + goto out; + } + if (produced > 0 && cb != NULL && delta.len > 0) { + int kind = SP_STREAM_TEXT; + + /* the line itself says which kind of delta this is */ + if (strstr(line, "\"reasoning_content\"") != NULL) + kind = SP_STREAM_THINK; + else if (strstr(line, "tool_calls") != NULL && + strstr(line, "\"content\"") == NULL) + kind = SP_STREAM_TOOL; + cb(cbctx, kind, delta.p); + } + } + if (pclose(p) != 0) { + sp_buf_printf(err, "openai: stream failed for %s: %.300s", + c->url, tail.p != NULL ? tail.p : ""); + unlink(path); + goto out; + } + unlink(path); + + if (!saw_data) { + sp_buf_printf(err, "openai: endpoint sent no SSE data: %.300s", + tail.p != NULL ? tail.p : "(empty)"); + goto out; + } + if (sp_sse_finish(sse, out, err) != 0) + goto out; + if (out->content != NULL && out->content[0] == '\0' && out->ncalls == 0) { + sp_buf_printf(err, "openai: stream ended with no answer: %.300s", + tail.p != NULL ? tail.p : "(empty)"); + sp_reply_free(out); + goto out; + } + rc = 0; +out: + sp_sse_free(sse); + sp_buf_free(&body); + sp_buf_free(&cmd); + sp_buf_free(&tail); + sp_buf_free(&delta); + return rc; +} + struct sp_transport sp_openai_transport(const char *url, const char *model, const char *api_key, const struct sp_registry *reg, long timeout_s) @@ -146,6 +266,7 @@ sp_openai_transport(const char *url, const char *model, const char *api_key, ctx.reg = reg; ctx.timeout_s = timeout_s > 0 ? timeout_s : 180; t.send = openai_send; + t.send_stream = openai_stream; t.ctx = &ctx; return t; } diff --git a/src/ui.c b/src/ui.c index 285fefe..b86b135 100644 --- a/src/ui.c +++ b/src/ui.c @@ -22,6 +22,8 @@ * Keys: Enter sends, Ctrl-L redraws, Ctrl-C drops the input line, Ctrl-D quits. */ #include +#include +#include #include #include #include @@ -80,9 +82,32 @@ struct turn { char steer[1024]; int have_steer; int steers; + struct sp_buf live; /* streamed text so far */ + struct sp_buf think; /* the model's reasoning so far */ + char tool[64]; /* last tool the model called */ + int tool_tick; pthread_mutex_t lock; }; +static void +stream_cb(void *ctx, int kind, const char *text) +{ + struct turn *t = ctx; + + if (text == NULL) + return; + pthread_mutex_lock(&t->lock); + if (kind == SP_STREAM_TEXT) { + (void)sp_buf_puts(&t->live, text); + } else if (kind == SP_STREAM_THINK) { + (void)sp_buf_puts(&t->think, text); + } else if (kind == SP_STREAM_TOOL) { + snprintf(t->tool, sizeof(t->tool), "%s", text); + t->tool_tick++; + } + pthread_mutex_unlock(&t->lock); +} + static int steer_cb(void *ctx, struct sp_buf *out) { @@ -128,6 +153,79 @@ init_colors(const struct sp_theme *t) sp_color_rgb(t->status[0], t->status[1], t->status[2], n)); } + +/* + * Text goes to curses as ASCII. + * + * Measured, not assumed: the vendored NetBSD curses emits Latin-1 bytes for + * wide characters (ü -> 0xFC) instead of re-encoding to the locale's charset, + * so a UTF-8 answer would reach the terminal as mojibake. ncurses passes the + * bytes through; this port does not. Until that is fixed in the library, the + * UI transliterates: the session log and the conversation keep the exact UTF-8, + * only the screen shows "gruen" instead of "grün". + */ +static void +ui_add_text(WINDOW *w, const char *s, int maxcols) +{ + char out[1024]; + size_t o = 0, i = 0; + + if (s == NULL) + return; + while (s[i] != '\0' && o < sizeof(out) - 8) { + unsigned char c = (unsigned char)s[i]; + + if (c < 0x80) { + out[o++] = (char)c; + i++; + continue; + } + /* UTF-8 sequences of two bytes cover Latin-1 and Latin Extended-A */ + if ((c & 0xe0) == 0xc0 && ((unsigned char)s[i + 1] & 0xc0) == 0x80) { + unsigned int cp = ((unsigned int)(c & 0x1f) << 6) | + (unsigned int)((unsigned char)s[i + 1] & 0x3f); + + switch (cp) { + case 0xe4: case 0xc4: /* ae AE */ + out[o++] = 'a'; out[o++] = 'e'; break; + case 0xf6: case 0xd6: /* oe OE */ + out[o++] = 'o'; out[o++] = 'e'; break; + case 0xfc: case 0xdc: /* ue UE */ + out[o++] = 'u'; out[o++] = 'e'; break; + case 0xdf: /* ss */ + out[o++] = 's'; out[o++] = 's'; break; + case 0xe0: case 0xe1: case 0xe2: case 0xe3: case 0xe5: + case 0xc0: case 0xc1: case 0xc2: case 0xc3: case 0xc5: + out[o++] = 'a'; break; /* a a a a a */ + case 0xe8: case 0xe9: case 0xea: case 0xeb: + case 0xc8: case 0xc9: case 0xca: case 0xcb: + out[o++] = 'e'; break; /* e e e e */ + case 0xec: case 0xed: case 0xee: case 0xef: + case 0xcc: case 0xcd: case 0xce: case 0xcf: + out[o++] = 'i'; break; /* i i i i */ + case 0xf2: case 0xf3: case 0xf4: case 0xf5: + case 0xd2: case 0xd3: case 0xd4: case 0xd5: + out[o++] = 'o'; break; /* o o o o */ + case 0xf9: case 0xfa: case 0xfb: + case 0xd9: case 0xda: case 0xdb: + out[o++] = 'u'; break; /* u u u */ + case 0xe7: case 0xc7: /* c C cedilla */ + out[o++] = 'c'; break; + case 0xf1: case 0xd1: /* n N tilde */ + out[o++] = 'n'; break; + default: + out[o++] = '?'; break; + } + i += 2; + continue; + } + out[o++] = '?'; + i++; + } + out[o] = '\0'; + waddnstr(w, out, maxcols); +} + static int entry_lines(int cols, const struct entry *e) { @@ -194,7 +292,7 @@ draw_history(struct ui_state *s) wattron(ui_hist, COLOR_PAIR(PAIR_ACCENT) | A_BOLD); else wattron(ui_hist, COLOR_PAIR(PAIR_DIM)); - waddnstr(ui_hist, render + off, rows * cols); + ui_add_text(ui_hist, render + off, rows * cols); wattrset(ui_hist, A_NORMAL); free(render); @@ -204,6 +302,64 @@ draw_history(struct ui_state *s) wnoutrefresh(ui_hist); } +/* + * The streaming turn is drawn as the last thing in the history pane: the tail + * of what has arrived so far. It is not an entry yet - entries are what was + * completed, and mixing the two would make the log look like it changed. + */ +/* + * The streaming turn is painted at the bottom of the history pane: the tail of + * what has arrived, wrapped over up to five rows, with the model's reasoning on + * one dim row above it. It is not an entry yet - entries are what was + * completed, and mixing the two would make the log look like it changed. + */ +static void +draw_live(struct ui_state *s, const char *text, const char *tool, + const char *think) +{ + int rows, cols, use; + size_t len, take, start; + + if ((text == NULL || text[0] == '\0') && + (think == NULL || think[0] == '\0')) + return; + getmaxyx(ui_hist, rows, cols); + if (rows < 4 || cols < 8) + return; + + len = text != NULL ? strlen(text) : 0; + use = rows - 1 < 5 ? rows - 1 : 5; + take = (size_t)use * (size_t)cols; + start = len > take ? len - take : 0; + + if (think != NULL && think[0] != '\0') { + size_t tlen = strlen(think); + size_t tstart = tlen > (size_t)(cols - 1) ? + tlen - (size_t)(cols - 1) : 0; + + wattron(ui_hist, COLOR_PAIR(PAIR_DIM)); + wmove(ui_hist, rows - use - 1 >= 0 ? rows - use - 1 : 0, 0); + ui_add_text(ui_hist, think + tstart, cols - 1); + wattroff(ui_hist, COLOR_PAIR(PAIR_DIM)); + } + if (len > 0) { + wattron(ui_hist, COLOR_PAIR(PAIR_ACCENT)); + wmove(ui_hist, rows - use, 0); + ui_add_text(ui_hist, text + start, (int)take); + wattroff(ui_hist, COLOR_PAIR(PAIR_ACCENT)); + } + if (tool != NULL && tool[0] != '\0') { + char head[96]; + + snprintf(head, sizeof(head), "tool %s", tool); + wattron(ui_hist, COLOR_PAIR(PAIR_MAIN) | A_BOLD); + mvwaddnstr(ui_hist, rows - 1, 0, head, cols - 1); + wattroff(ui_hist, A_BOLD); + } + (void)s; + wnoutrefresh(ui_hist); +} + static void sidebar_heading(int *y, int cols, const char *text) { @@ -341,6 +497,11 @@ sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *theme_name, return 1; } + /* + * Without this, curses treats every byte above 0x7f as garbage: German + * umlauts and every UTF-8 answer would arrive as replacement characters. + */ + setlocale(LC_ALL, ""); initscr(); cbreak(); noecho(); @@ -400,10 +561,18 @@ sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *theme_name, } continue; } - if (ch >= 32 && ch < 127 && - len < sizeof(input) - 1) { + if (ch >= 32 && ch != 127 && + len < sizeof(input) - 2) { + /* + * Bytes, not wide chars: a UTF-8 sequence arrives + * as several keys. The line is redrawn from the + * buffer so curses converts the whole string. + */ input[len++] = (char)ch; - waddch(ui_input, (chtype)ch); + input[len] = '\0'; + werase(ui_input); + mvwaddstr(ui_input, 0, 0, "> "); + ui_add_text(ui_input, input, getmaxx(ui_input) - 3); wrefresh(ui_input); } } @@ -439,10 +608,14 @@ sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *theme_name, tu.text = input; sp_buf_init(&tu.answer); sp_buf_init(&tu.err); + sp_buf_init(&tu.live); + sp_buf_init(&tu.think); pthread_mutex_init(&tu.lock, NULL); cfg.cancel = &tu.cancel; cfg.steer = steer_cb; cfg.steer_ctx = &tu; + cfg.stream = stream_cb; + cfg.stream_ctx = &tu; ag->cfg = &cfg; if (pthread_create(&th, NULL, turn_thread, &tu) != 0) { @@ -475,6 +648,32 @@ sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *theme_name, c = wgetch(ui_input); if (c == ERR) { + char live[4096]; + char think[2048]; + char tool[64]; + size_t llen2 = 0, tlen2 = 0; + + pthread_mutex_lock(&tu.lock); + if (tu.live.len > 0) { + llen2 = tu.live.len; + if (llen2 > sizeof(live) - 1) + llen2 = sizeof(live) - 1; + memcpy(live, tu.live.p, llen2); + } + if (tu.think.len > 0) { + tlen2 = tu.think.len; + if (tlen2 > sizeof(think) - 1) + tlen2 = sizeof(think) - 1; + memcpy(think, tu.think.p, tlen2); + } + snprintf(tool, sizeof(tool), "%s", + tu.tool); + pthread_mutex_unlock(&tu.lock); + live[llen2] = '\0'; + think[tlen2] = '\0'; + draw_history(&s); + draw_live(&s, live, tool, think); + doupdate(); /* redraw the clock in the status bar */ clock_gettime(CLOCK_MONOTONIC, &now); ms = (long)((now.tv_sec - t0.tv_sec) * @@ -523,8 +722,8 @@ sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *theme_name, line[llen] = '\0'; continue; } - if (c >= 32 && c < 127 && - llen < sizeof(line) - 1) { + if (c >= 32 && c != 127 && + llen < sizeof(line) - 2) { line[llen++] = (char)c; line[llen] = '\0'; } @@ -556,6 +755,8 @@ sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *theme_name, } sp_buf_free(&tu.answer); sp_buf_free(&tu.err); + sp_buf_free(&tu.live); + sp_buf_free(&tu.think); pthread_mutex_destroy(&tu.lock); } } diff --git a/tests/test_cli b/tests/test_cli index 62b9455..2a7b3f3 100755 Binary files a/tests/test_cli and b/tests/test_cli differ diff --git a/tests/test_compactor b/tests/test_compactor index a329d39..2d24258 100755 Binary files a/tests/test_compactor and b/tests/test_compactor differ diff --git a/tests/test_openai b/tests/test_openai index b323915..c59cdc6 100755 Binary files a/tests/test_openai and b/tests/test_openai differ diff --git a/tests/test_openai.c b/tests/test_openai.c index 70161ac..9bcd1e2 100644 --- a/tests/test_openai.c +++ b/tests/test_openai.c @@ -50,13 +50,16 @@ main(void) /* ---- request ---- */ CHECK(sp_conv_push(&conv, "system", NULL, "be brief") == 0); CHECK(sp_conv_push(&conv, "user", NULL, "say \"hi\"") == 0); - CHECK(sp_openai_request(&conv, "m1", ®, &req) == 0); + CHECK(sp_openai_request(&conv, "m1", ®, 0, &req) == 0); CHECK(strstr(req.p, "\"model\":\"m1\"") != NULL); CHECK(strstr(req.p, "\"role\":\"system\"") != NULL); CHECK(strstr(req.p, "\"content\":\"say \\\"hi\\\"\"") != NULL); CHECK(strstr(req.p, "\"tools\":[") != NULL); CHECK(strstr(req.p, "\"name\":\"echo\"") != NULL); CHECK(strstr(req.p, "\"stream\":false") != NULL); + /* streaming switches the flag, nothing else */ + CHECK(sp_openai_request(&conv, "m1", ®, 1, &req) == 0); + CHECK(strstr(req.p, "\"stream\":true") != NULL); /* tool messages carry the call id, and nothing else claims to */ { @@ -68,7 +71,7 @@ main(void) m.call_id = "call-1"; m.content = "pong"; CHECK(sp_conv_add(&conv, &m) == 0); - CHECK(sp_openai_request(&conv, "m1", ®, &req) == 0); + CHECK(sp_openai_request(&conv, "m1", ®, 0, &req) == 0); CHECK(strstr(req.p, "\"tool_call_id\":\"call-1\"") != NULL); } @@ -82,7 +85,7 @@ main(void) m.calls = "[{\"id\":\"call-1\",\"type\":\"function\"," "\"function\":{\"name\":\"echo\",\"arguments\":\"{}\"}}]"; CHECK(sp_conv_add(&conv, &m) == 0); - CHECK(sp_openai_request(&conv, "m1", ®, &req) == 0); + CHECK(sp_openai_request(&conv, "m1", ®, 0, &req) == 0); CHECK(strstr(req.p, "\"tool_calls\":[{\"id\":\"call-1\"") != NULL); } diff --git a/tests/test_plugin b/tests/test_plugin index dfb0cea..49fabe2 100755 Binary files a/tests/test_plugin and b/tests/test_plugin differ diff --git a/tests/test_sse b/tests/test_sse new file mode 100755 index 0000000..91203bc Binary files /dev/null and b/tests/test_sse differ diff --git a/tests/test_sse.c b/tests/test_sse.c new file mode 100644 index 0000000..278a642 --- /dev/null +++ b/tests/test_sse.c @@ -0,0 +1,124 @@ +/* + * splinter -- SSE accumulation tests, fed with recorded lines. + * + * No socket: the parser takes one line at a time, so these are the exact lines + * an OpenAI-compatible endpoint sends, in the order it sends them. + */ +#include +#include + +#include "splinter.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 failures_now; + +int +main(void) +{ + struct sp_sse *s; + struct sp_buf out, err; + struct sp_reply r; + + (void)failures_now; + if (sp_buf_init(&out) != 0 || sp_buf_init(&err) != 0) + return 1; + + /* ---- plain text stream ---- */ + s = sp_sse_new(); + CHECK(s != NULL); + sp_buf_clear(&out); + CHECK(sp_sse_line(s, ": keepalive\n", &out, &err) == 0); + CHECK(sp_sse_line(s, "data: {\"choices\":[{\"delta\":{\"role\":" + "\"assistant\"}}]}\n", &out, &err) == 0); + CHECK(sp_sse_line(s, "data: {\"choices\":[{\"delta\":{\"content\":" + "\"Hal\"}}]}\n", &out, &err) == 1); + CHECK(strcmp(out.p, "Hal") == 0); + sp_buf_clear(&out); + CHECK(sp_sse_line(s, "data: {\"choices\":[{\"delta\":{\"content\":" + "\"lo\"}}]}\n", &out, &err) == 1); + CHECK(strcmp(out.p, "lo") == 0); + CHECK(sp_sse_line(s, "data: [DONE]\n", &out, &err) == 0); + CHECK(sp_sse_done(s) == 1); + memset(&r, 0, sizeof(r)); + CHECK(sp_sse_finish(s, &r, &err) == 0); + CHECK(r.content != NULL && strcmp(r.content, "Hallo") == 0); + CHECK(r.ncalls == 0); + CHECK(r.calls_json == NULL); + sp_reply_free(&r); + sp_sse_free(s); + + /* ---- a tool call in pieces, the way OpenAI sends them ---- */ + s = sp_sse_new(); + sp_buf_clear(&out); + CHECK(sp_sse_line(s, "data: {\"choices\":[{\"delta\":{\"tool_calls\":" + "[{\"index\":0,\"id\":\"call-a\",\"function\":{\"name\":\"echo\"," + "\"arguments\":\"\"}}]}}]}\n", &out, &err) == 1); + CHECK(strcmp(out.p, "echo") == 0); + CHECK(sp_sse_tool_start(s, 0) != NULL); + sp_buf_clear(&out); + CHECK(sp_sse_line(s, "data: {\"choices\":[{\"delta\":{\"tool_calls\":" + "[{\"index\":0,\"function\":{\"arguments\":\"{\\\"text\\\":\"}}]}}]}\n", + &out, &err) == 0); + sp_buf_clear(&out); + CHECK(sp_sse_line(s, "data: {\"choices\":[{\"delta\":{\"tool_calls\":" + "[{\"index\":0,\"function\":{\"arguments\":\"\\\"ping\\\"}\"}}]}}]}\n", + &out, &err) == 0); + CHECK(sp_sse_line(s, "data: [DONE]\n", &out, &err) == 0); + memset(&r, 0, sizeof(r)); + CHECK(sp_sse_finish(s, &r, &err) == 0); + CHECK(r.ncalls == 1); + CHECK(strcmp(r.calls[0].id, "call-a") == 0); + CHECK(strcmp(r.calls[0].name, "echo") == 0); + CHECK(strcmp(r.calls[0].args, "{\"text\":\"ping\"}") == 0); + /* the reconstructed array is valid JSON text with the same values */ + CHECK(r.calls_json != NULL); + CHECK(strstr(r.calls_json, "\"call-a\"") != NULL); + CHECK(strstr(r.calls_json, "\\\"text\\\":\\\"ping\\\"") != NULL); + sp_reply_free(&r); + sp_sse_free(s); + + /* ---- two calls in one turn keep their indexes apart ---- */ + s = sp_sse_new(); + sp_buf_clear(&out); + CHECK(sp_sse_line(s, "data: {\"choices\":[{\"delta\":{\"tool_calls\":" + "[{\"index\":0,\"id\":\"c0\",\"function\":{\"name\":\"a\"," + "\"arguments\":\"{}\"}},{\"index\":1,\"id\":\"c1\",\"function\":" + "{\"name\":\"b\",\"arguments\":\"{}\"}}]}}]}\n", &out, &err) == 1); + memset(&r, 0, sizeof(r)); + CHECK(sp_sse_finish(s, &r, &err) == 0); + CHECK(r.ncalls == 2); + CHECK(strcmp(r.calls[0].name, "a") == 0); + CHECK(strcmp(r.calls[1].name, "b") == 0); + sp_reply_free(&r); + sp_sse_free(s); + + /* ---- a broken data line is an error that quotes itself ---- */ + s = sp_sse_new(); + sp_buf_clear(&err); + CHECK(sp_sse_line(s, "data: {kaputt\n", &out, &err) == -1); + CHECK(strstr(err.p, "unparseable data line") != NULL); + sp_sse_free(s); + + /* ---- non-data lines carry nothing and are not errors ---- */ + s = sp_sse_new(); + sp_buf_clear(&err); + CHECK(sp_sse_line(s, "event: ping\n", &out, &err) == 0); + CHECK(sp_sse_line(s, "\n", &out, &err) == 0); + CHECK(err.len == 0); + sp_sse_free(s); + + sp_buf_free(&out); + sp_buf_free(&err); + + if (failures == 0) + printf("test_sse: ok\n"); + return failures == 0 ? 0 : 1; +}