diff --git a/src/backend/sse.c b/src/backend/sse.c index c2ce7a0..c01f951 100644 --- a/src/backend/sse.c +++ b/src/backend/sse.c @@ -374,8 +374,20 @@ sp_sse_line(struct sp_sse *s, const char *line, struct sp_buf *out, 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); + if (index < 0) { + /* + * A bridge that replays a completed non-streaming + * message in one delta has no index on its calls. + * Several entries in such a delta are distinct + * calls, not fragments of the last one; a lone + * entry is the next piece of the last call. + */ + if (n > 1) + index = (int)i; + else + index = (int)(s->ncalls == 0 ? 0 : + s->ncalls - 1); + } slot = call_slot(s, (size_t)index); if (slot == NULL) { mcp_json_free(v); diff --git a/tests/test_sse.c b/tests/test_sse.c index 799384c..30c5463 100644 --- a/tests/test_sse.c +++ b/tests/test_sse.c @@ -117,6 +117,34 @@ main(void) sp_reply_free(&r); sp_sse_free(s); + /* + * ---- a bridge that replays a whole non-stream message in one delta ---- + * + * Non-streaming tool_calls carry no index. Several entries in one delta are + * then distinct calls, not pieces of the same one: junction used to emit + * exactly that and splinter merged four calls into one whose arguments were + * several JSON objects ("{}{...}{...}"). A lone index-less entry stays the + * next fragment of the last call, which the piecewise test above covers. + */ + s = sp_sse_new(); + sp_buf_clear(&out); + CHECK(sp_sse_line(s, "data: {\"choices\":[{\"delta\":{\"tool_calls\":[" + "{\"id\":\"c0\",\"function\":{\"name\":\"a\",\"arguments\":\"{}\"}}," + "{\"id\":\"c1\",\"function\":{\"name\":\"b\",\"arguments\":\"{}\"}}," + "{\"id\":\"c2\",\"function\":{\"name\":\"c\",\"arguments\":\"{}\"}}" + "]}}]}\n", &out, &err) > 0); + memset(&r, 0, sizeof(r)); + CHECK(sp_sse_finish(s, &r, &err) == 0); + CHECK(r.ncalls == 3); + CHECK(strcmp(r.calls[0].name, "a") == 0); + CHECK(strcmp(r.calls[1].name, "b") == 0); + CHECK(strcmp(r.calls[2].name, "c") == 0); + CHECK(strcmp(r.calls[0].args, "{}") == 0); + CHECK(strcmp(r.calls[1].args, "{}") == 0); + CHECK(strcmp(r.calls[2].args, "{}") == 0); + sp_reply_free(&r); + sp_sse_free(s); + /* ---- usage carries the cache share of the prompt ---- */ s = sp_sse_new(); sp_buf_clear(&out);