xonecas.io
7814
Ta

tiny-c-agent / commit 6b67007

chore: agent gardening

xonecas2026-10-03 6b67007c77010bc32d35e74a94441d11f403b3ca parent e87aec3

37 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

Makefile+4−12
@@ -13,20 +13,17 @@ WARN := -Wall -Wextra -Wshadow -Wstrict-prototypes -Wmissing-prototypes -Wpoi
1313 BUILD := build
1414 BIN := $(BUILD)/cage
1515
16-PKGS := libuv libcurl ncursesw yyjson tree-sitter \
16+PKGS := libcurl yyjson tree-sitter \
1717 tree-sitter-javascript tree-sitter-bash \
1818 tree-sitter-markdown tree-sitter-markdown-inline
1919
20-TSJSON := third_party/tree-sitter-json
21-
2220 SRCS := $(shell find src -name '*.c' | sort)
2321 OBJS := $(patsubst src/%.c,$(BUILD)/obj/%.o,$(SRCS))
24-TSJSON_OBJ := $(BUILD)/obj/$(TSJSON)/src/parser.o
25-DEPS := $(OBJS:.o=.d) $(TSJSON_OBJ:.o=.d)
22+DEPS := $(OBJS:.o=.d)
2623
2724 BASE := -std=$(STD) $(OPT) -pthread
2825
29-CPPFLAGS += -D_GNU_SOURCE -Isrc -I$(TSJSON)/src -MMD -MP
26+CPPFLAGS += -D_GNU_SOURCE -Isrc -MMD -MP
3027 CFLAGS += $(BASE) $(WARN) $(shell pkg-config --cflags $(PKGS))
3128 LDLIBS += $(shell pkg-config --libs $(PKGS)) -pthread
3229
@@ -38,18 +35,13 @@ all: $(BIN)
3835 catalog:
3936 python3 tools/gen_catalog.py
4037
41-$(BIN): $(OBJS) $(TSJSON_OBJ)
38+$(BIN): $(OBJS)
4239 $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(LDLIBS)
4340
4441 $(BUILD)/obj/%.o: src/%.c
4542 @mkdir -p $(dir $@)
4643 $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<
4744
48-# Vendored grammars are generated code and are built without the project warnings.
49-$(TSJSON_OBJ): $(TSJSON)/src/parser.c
50- @mkdir -p $(dir $@)
51- $(CC) $(CPPFLAGS) $(BASE) -c -o $@ $<
52-
5345 deps:
5446 @for p in $(PKGS); do \
5547 if pkg-config --exists $$p; then \
src/agent.c+2−33
@@ -11,6 +11,7 @@
1111 #include <yyjson.h>
1212
1313 #include "diff.h"
14+#include "util.h"
1415
1516 // Per-turn state passed to the provider and tool callbacks.
1617 typedef struct {
@@ -18,38 +19,6 @@ typedef struct {
1819 bool streaming;
1920 } turn_state;
2021
21-static void *xmalloc(size_t n) {
22- void *p = malloc(n);
23- if (!p) abort();
24- return p;
25-}
26-
27-static char *xstrdup(const char *s) {
28- size_t n = strlen(s) + 1;
29- char *p = xmalloc(n);
30- memcpy(p, s, n);
31- return p;
32-}
33-
34-typedef struct {
35- char *data;
36- size_t len;
37- size_t cap;
38-} buf;
39-
40-static void buf_add(buf *b, const char *p, size_t n) {
41- if (b->len + n + 1 > b->cap) {
42- size_t cap = b->cap ? b->cap : 64;
43- while (cap < b->len + n + 1) cap *= 2;
44- b->data = realloc(b->data, cap);
45- if (!b->data) abort();
46- b->cap = cap;
47- }
48- memcpy(b->data + b->len, p, n);
49- b->len += n;
50- b->data[b->len] = '\0';
51-}
52-
5322 // ---- event helpers --------------------------------------------------------
5423
5524 static void emit(cage_agent *a, const cage_event *e) {
@@ -265,7 +234,7 @@ void cage_agent_turn(cage_agent *a, const char *input) {
265234 }
266235
267236 // Steering is held until every result of this assistant turn has landed.
268- buf held = {0};
237+ cage_buf held = {0};
269238 bool cancelled = false;
270239 for (size_t i = 0; i < asst.blocks_len && !cancelled; i++) {
271240 cage_block *b = &asst.blocks[i];
src/api.h+18−0
@@ -3,8 +3,26 @@
33 #ifndef CAGE_API_H
44 #define CAGE_API_H
55
6+#include <yyjson.h>
7+
68 #include "provider.h"
79
10+// Adds a tool's "name", "description", and schema (under `params_key`) to `obj`.
11+// Shared by every adapter's tool serialization.
12+void cage_json_tool(yyjson_mut_doc *doc, yyjson_mut_val *obj, const cage_tool *t,
13+ const char *params_key);
14+
15+// Emits one delta to the adapter's stream callback, if any.
16+void cage_emit_delta(cage_stream_fn emit, void *user, cage_stream_type type, const char *delta);
17+
18+// Appends a text/thinking block when `text` is non-NULL and non-empty.
19+void cage_add_text_block(cage_message *out, cage_block_type type, const char *text);
20+
21+// Appends a tool-call block (defaulting empty arguments to "{}") and emits the
22+// corresponding CAGE_STREAM_TOOL_CALL event.
23+void cage_add_tool_block(cage_message *out, const char *id, const char *name,
24+ const char *args, cage_stream_fn emit, void *user);
25+
826 int cage_openai_completions_stream(const cage_model *model, const cage_context *ctx,
927 const cage_stream_opts *opts,
1028 cage_stream_fn emit, void *user,
src/api/anthropic_messages.c+27−142
@@ -2,7 +2,6 @@
22
33 #include "api.h"
44
5-#include <stdarg.h>
65 #include <stdio.h>
76 #include <stdlib.h>
87 #include <string.h>
@@ -10,51 +9,10 @@
109 #include <yyjson.h>
1110
1211 #include "http.h"
12+#include "util.h"
1313
1414 #define ANTHROPIC_VERSION "2023-06-01"
1515
16-static void *xmalloc(size_t n) {
17- void *p = malloc(n);
18- if (!p) abort();
19- return p;
20-}
21-
22-static char *xstrdup(const char *s) {
23- size_t n = strlen(s) + 1;
24- char *p = xmalloc(n);
25- memcpy(p, s, n);
26- return p;
27-}
28-
29-static int fail(char **err, const char *fmt, ...) {
30- char detail[512];
31- va_list ap;
32- va_start(ap, fmt);
33- vsnprintf(detail, sizeof detail, fmt, ap);
34- va_end(ap);
35- *err = xstrdup(detail);
36- return -1;
37-}
38-
39-typedef struct {
40- char *data;
41- size_t len;
42- size_t cap;
43-} buf;
44-
45-static void buf_add(buf *b, const char *p, size_t n) {
46- if (b->len + n + 1 > b->cap) {
47- size_t cap = b->cap ? b->cap : 64;
48- while (cap < b->len + n + 1) cap *= 2;
49- b->data = realloc(b->data, cap);
50- if (!b->data) abort();
51- b->cap = cap;
52- }
53- memcpy(b->data + b->len, p, n);
54- b->len += n;
55- b->data[b->len] = '\0';
56-}
57-
5816 // ---- request --------------------------------------------------------------
5917
6018 static void add_image_block(yyjson_mut_doc *doc, yyjson_mut_val *content,
@@ -84,7 +42,7 @@ static void add_tool_result(yyjson_mut_doc *doc, yyjson_mut_val *messages, const
8442
8543 bool has_images = cage_message_has_image(m);
8644 if (!has_images) {
87- buf t = {0};
45+ cage_buf t = {0};
8846 for (size_t i = 0; i < m->blocks_len; i++)
8947 if (m->blocks[i].type == CAGE_BLOCK_TEXT && m->blocks[i].text)
9048 buf_add(&t, m->blocks[i].text, strlen(m->blocks[i].text));
@@ -149,15 +107,7 @@ static void add_tools(yyjson_mut_doc *doc, yyjson_mut_val *root, const cage_cont
149107 const cage_tool *t = &ctx->tools[i];
150108 yyjson_mut_val *tool = yyjson_mut_obj(doc);
151109 yyjson_mut_arr_add_val(tools, tool);
152- yyjson_mut_obj_add_strcpy(doc, tool, "name", t->name);
153- yyjson_mut_obj_add_strcpy(doc, tool, "description", t->description ? t->description : "");
154- const char *params = t->parameters ? t->parameters : "{}";
155- yyjson_doc *pdoc = yyjson_read(params, strlen(params), 0);
156- if (pdoc) {
157- yyjson_mut_val *copy = yyjson_val_mut_copy(doc, yyjson_doc_get_root(pdoc));
158- yyjson_mut_obj_add_val(doc, tool, "input_schema", copy);
159- yyjson_doc_free(pdoc);
160- }
110+ cage_json_tool(doc, tool, t, "input_schema");
161111 }
162112 }
163113
@@ -224,10 +174,10 @@ enum { BLK_TEXT, BLK_THINKING, BLK_TOOL };
224174
225175 typedef struct {
226176 int type;
227- buf text;
177+ cage_buf text;
228178 char *id;
229179 char *name;
230- buf args;
180+ cage_buf args;
231181 } block_acc;
232182
233183 typedef struct {
@@ -241,12 +191,6 @@ typedef struct {
241191 void *user;
242192 } anth_state;
243193
244-static void emit_delta(anth_state *st, cage_stream_type type, const char *delta) {
245- if (!st->emit) return;
246- cage_stream_event ev = {.type = type, .delta = delta};
247- st->emit(&ev, st->user);
248-}
249-
250194 static block_acc *block_at(anth_state *st, size_t index) {
251195 if (index >= st->blocks_len) {
252196 st->blocks = realloc(st->blocks, (index + 1) * sizeof *st->blocks);
@@ -257,12 +201,8 @@ static block_acc *block_at(anth_state *st, size_t index) {
257201 return &st->blocks[index];
258202 }
259203
260-static void set_str(char **dst, const char *src) {
261- free(*dst);
262- *dst = xstrdup(src ? src : "");
263-}
264-
265-static void handle_data(anth_state *st, const char *json, size_t len) {
204+static void on_data(const char *json, size_t len, void *user) {
205+ anth_state *st = user;
266206 yyjson_doc *doc = yyjson_read(json, len, 0);
267207 if (!doc) {
268208 if (!st->error) st->error = xstrdup("stream: invalid JSON chunk");
@@ -275,7 +215,7 @@ static void handle_data(anth_state *st, const char *json, size_t len) {
275215 if (strcmp(type, "error") == 0) {
276216 yyjson_val *err = yyjson_obj_get(root, "error");
277217 yyjson_val *m = yyjson_is_obj(err) ? yyjson_obj_get(err, "message") : NULL;
278- set_str(&st->error, yyjson_is_str(m) ? yyjson_get_str(m) : "stream: provider error");
218+ cage_set_str(&st->error, yyjson_is_str(m) ? yyjson_get_str(m) : "stream: provider error");
279219 } else if (strcmp(type, "message_start") == 0) {
280220 yyjson_val *msg = yyjson_obj_get(root, "message");
281221 yyjson_val *usage = yyjson_is_obj(msg) ? yyjson_obj_get(msg, "usage") : NULL;
@@ -298,8 +238,8 @@ static void handle_data(anth_state *st, const char *json, size_t len) {
298238 b->type = BLK_TOOL;
299239 yyjson_val *id = yyjson_obj_get(cb, "id");
300240 yyjson_val *nm = yyjson_obj_get(cb, "name");
301- if (yyjson_is_str(id)) set_str(&b->id, yyjson_get_str(id));
302- if (yyjson_is_str(nm)) set_str(&b->name, yyjson_get_str(nm));
241+ if (yyjson_is_str(id)) cage_set_str(&b->id, yyjson_get_str(id));
242+ if (yyjson_is_str(nm)) cage_set_str(&b->name, yyjson_get_str(nm));
303243 } else if (strcmp(bts, "thinking") == 0 || strcmp(bts, "redacted_thinking") == 0) {
304244 b->type = BLK_THINKING;
305245 } else {
@@ -324,13 +264,13 @@ static void handle_data(anth_state *st, const char *json, size_t len) {
324264 yyjson_val *t = yyjson_obj_get(d, "text");
325265 if (yyjson_is_str(t) && yyjson_get_str(t)[0]) {
326266 buf_add(&b->text, yyjson_get_str(t), strlen(yyjson_get_str(t)));
327- emit_delta(st, CAGE_STREAM_TEXT_DELTA, yyjson_get_str(t));
267+ cage_emit_delta(st->emit, st->user, CAGE_STREAM_TEXT_DELTA, yyjson_get_str(t));
328268 }
329269 } else if (strcmp(dts, "thinking_delta") == 0) {
330270 yyjson_val *t = yyjson_obj_get(d, "thinking");
331271 if (yyjson_is_str(t) && yyjson_get_str(t)[0]) {
332272 buf_add(&b->text, yyjson_get_str(t), strlen(yyjson_get_str(t)));
333- emit_delta(st, CAGE_STREAM_REASONING_DELTA, yyjson_get_str(t));
273+ cage_emit_delta(st->emit, st->user, CAGE_STREAM_REASONING_DELTA, yyjson_get_str(t));
334274 }
335275 } else if (strcmp(dts, "input_json_delta") == 0) {
336276 yyjson_val *p = yyjson_obj_get(d, "partial_json");
@@ -339,7 +279,7 @@ static void handle_data(anth_state *st, const char *json, size_t len) {
339279 } else if (strcmp(type, "message_delta") == 0) {
340280 yyjson_val *d = yyjson_obj_get(root, "delta");
341281 yyjson_val *sr = yyjson_is_obj(d) ? yyjson_obj_get(d, "stop_reason") : NULL;
342- if (yyjson_is_str(sr)) set_str(&st->stop_reason, yyjson_get_str(sr));
282+ if (yyjson_is_str(sr)) cage_set_str(&st->stop_reason, yyjson_get_str(sr));
343283 yyjson_val *usage = yyjson_obj_get(root, "usage");
344284 if (yyjson_is_obj(usage)) {
345285 yyjson_val *v;
@@ -349,10 +289,6 @@ static void handle_data(anth_state *st, const char *json, size_t len) {
349289 yyjson_doc_free(doc);
350290 }
351291
352-static void on_data(const char *json, size_t len, void *user) {
353- handle_data(user, json, len);
354-}
355-
356292 static void free_state(anth_state *st) {
357293 for (size_t i = 0; i < st->blocks_len; i++) {
358294 free(st->blocks[i].text.data);
@@ -379,30 +315,15 @@ static void finalize(anth_state *st, cage_message *out) {
379315 }
380316 for (size_t i = 0; i < st->blocks_len; i++) {
381317 block_acc *b = &st->blocks[i];
382- if (b->type == BLK_THINKING && b->text.len > 0) {
383- cage_block *blk = cage_message_add_block(out, CAGE_BLOCK_THINKING);
384- blk->text = xstrdup(b->text.data);
385- } else if (b->type == BLK_TEXT && b->text.len > 0) {
386- cage_block *blk = cage_message_add_block(out, CAGE_BLOCK_TEXT);
387- blk->text = xstrdup(b->text.data);
388- }
318+ if (b->type == BLK_THINKING)
319+ cage_add_text_block(out, CAGE_BLOCK_THINKING, b->text.data);
320+ else if (b->type == BLK_TEXT)
321+ cage_add_text_block(out, CAGE_BLOCK_TEXT, b->text.data);
389322 }
390323 for (size_t i = 0; i < st->blocks_len; i++) {
391324 block_acc *b = &st->blocks[i];
392325 if (b->type != BLK_TOOL) continue;
393- cage_block *blk = cage_message_add_block(out, CAGE_BLOCK_TOOL_CALL);
394- blk->tool_call_id = xstrdup(b->id ? b->id : "");
395- blk->tool_name = xstrdup(b->name ? b->name : "");
396- blk->arguments = xstrdup(b->args.len ? b->args.data : "{}");
397- if (st->emit) {
398- cage_stream_event ev = {
399- .type = CAGE_STREAM_TOOL_CALL,
400- .tool_call_id = blk->tool_call_id,
401- .tool_name = blk->tool_name,
402- .tool_arguments = blk->arguments,
403- };
404- st->emit(&ev, st->user);
405- }
326+ cage_add_tool_block(out, b->id, b->name, b->args.len ? b->args.data : NULL, st->emit, st->user);
406327 }
407328 out->tokens_in = st->tokens_in;
408329 out->tokens_out = st->tokens_out;
@@ -412,16 +333,6 @@ static void finalize(anth_state *st, cage_message *out) {
412333
413334 // ---- transport ------------------------------------------------------------
414335
415-static char *endpoint_url(const char *base) {
416- if (!base || !base[0]) return NULL;
417- size_t n = strlen(base);
418- const char *path = "v1/messages";
419- bool slash = base[n - 1] == '/';
420- size_t size = n + strlen(path) + 2;
421- char *url = xmalloc(size);
422- snprintf(url, size, slash ? "%s%s" : "%s/%s", base, path);
423- return url;
424-}
425336
426337 int cage_anthropic_messages_stream(const cage_model *model, const cage_context *ctx,
427338 const cage_stream_opts *opts,
@@ -432,59 +343,33 @@ int cage_anthropic_messages_stream(const cage_model *model, const cage_context *
432343 memset(out, 0, sizeof *out);
433344 out->role = CAGE_ROLE_ASSISTANT;
434345
435- char *url = endpoint_url(model->base_url);
436- if (!url) return fail(err, "provider: no base url");
346+ char *url = cage_url_endpoint(model->base_url, "v1/messages");
347+ if (!url) return cage_fail(err, "provider: no base url");
437348 char *body = build_request(model, ctx, opts);
438349 if (!body) {
439350 free(url);
440- return fail(err, "provider: cannot build request");
351+ return cage_fail(err, "provider: cannot build request");
441352 }
442353
443354 anth_state st = {0};
444355 st.emit = emit;
445356 st.user = user;
446357
447- char *auth = NULL;
448- struct curl_slist *headers = NULL;
449- headers = curl_slist_append(headers, "Content-Type: application/json");
450- headers = curl_slist_append(headers, "Accept: text/event-stream");
451- headers = curl_slist_append(headers, "anthropic-version: " ANTHROPIC_VERSION);
452- if (model->api_key && model->api_key[0]) {
453- size_t n = strlen(model->api_key) + 12;
454- auth = xmalloc(n);
455- snprintf(auth, n, "x-api-key: %s", model->api_key);
456- headers = curl_slist_append(headers, auth);
457- }
458-
459- cage_http_request req = {
460- .url = url,
461- .body = body,
462- .headers = headers,
463- .cancel = cancel,
464- .on_data = on_data,
465- .user = &st,
466- };
467- cage_http_stream(&req);
358+ const char *extra[] = {"anthropic-version: " ANTHROPIC_VERSION, NULL};
359+ cage_api_result r = cage_api_post(url, body, "x-api-key: ", model->api_key,
360+ extra, cancel, on_data, &st, st.error, err);
468361
469362 int rc = 0;
470- if (req.aborted) {
363+ if (r == CAGE_API_ABORTED) {
471364 out->stop_reason = xstrdup("aborted");
472- } else if (req.error) {
473- *err = req.error;
474- req.error = NULL;
365+ } else if (r == CAGE_API_TRANSPORT_ERROR) {
475366 rc = -1;
476- } else if (st.error) {
367+ } else if (r == CAGE_API_STREAM_ERROR) {
477368 out->stop_reason = xstrdup("error");
478369 out->error_message = xstrdup(st.error);
479370 } else {
480371 finalize(&st, out);
481372 }
482-
483- curl_slist_free_all(headers);
484- free(auth);
485- free(req.error);
486- free(url);
487- free(body);
488373 free_state(&st);
489374 return rc;
490375 }
src/api/google_generative_ai.c+22−129
@@ -2,7 +2,6 @@
22
33 #include "api.h"
44
5-#include <stdarg.h>
65 #include <stdio.h>
76 #include <stdlib.h>
87 #include <string.h>
@@ -10,48 +9,7 @@
109 #include <yyjson.h>
1110
1211 #include "http.h"
13-
14-static void *xmalloc(size_t n) {
15- void *p = malloc(n);
16- if (!p) abort();
17- return p;
18-}
19-
20-static char *xstrdup(const char *s) {
21- size_t n = strlen(s) + 1;
22- char *p = xmalloc(n);
23- memcpy(p, s, n);
24- return p;
25-}
26-
27-static int fail(char **err, const char *fmt, ...) {
28- char detail[512];
29- va_list ap;
30- va_start(ap, fmt);
31- vsnprintf(detail, sizeof detail, fmt, ap);
32- va_end(ap);
33- *err = xstrdup(detail);
34- return -1;
35-}
36-
37-typedef struct {
38- char *data;
39- size_t len;
40- size_t cap;
41-} buf;
42-
43-static void buf_add(buf *b, const char *p, size_t n) {
44- if (b->len + n + 1 > b->cap) {
45- size_t cap = b->cap ? b->cap : 64;
46- while (cap < b->len + n + 1) cap *= 2;
47- b->data = realloc(b->data, cap);
48- if (!b->data) abort();
49- b->cap = cap;
50- }
51- memcpy(b->data + b->len, p, n);
52- b->len += n;
53- b->data[b->len] = '\0';
54-}
12+#include "util.h"
5513
5614 // ---- request --------------------------------------------------------------
5715
@@ -122,10 +80,7 @@ static void add_tool_results(yyjson_mut_doc *doc, yyjson_mut_val *contents,
12280 yyjson_mut_obj_add_val(doc, o, "parts", parts);
12381 for (size_t i = from; i < to; i++) {
12482 const cage_message *m = &ctx->messages[i];
125- buf t = {0};
126- for (size_t k = 0; k < m->blocks_len; k++)
127- if (m->blocks[k].type == CAGE_BLOCK_TEXT && m->blocks[k].text)
128- buf_add(&t, m->blocks[k].text, strlen(m->blocks[k].text));
83+ char *t = cage_message_text(m);
12984 yyjson_mut_val *p = yyjson_mut_obj(doc);
13085 yyjson_mut_arr_add_val(parts, p);
13186 yyjson_mut_val *fr = yyjson_mut_obj(doc);
@@ -133,8 +88,8 @@ static void add_tool_results(yyjson_mut_doc *doc, yyjson_mut_val *contents,
13388 yyjson_mut_obj_add_strcpy(doc, fr, "name", tool_name_for(ctx, m->tool_call_id));
13489 yyjson_mut_val *resp = yyjson_mut_obj(doc);
13590 yyjson_mut_obj_add_val(doc, fr, "response", resp);
136- yyjson_mut_obj_add_strcpy(doc, resp, m->is_error ? "error" : "output", t.data ? t.data : "");
137- free(t.data);
91+ yyjson_mut_obj_add_strcpy(doc, resp, m->is_error ? "error" : "output", t);
92+ free(t);
13893 }
13994 }
14095
@@ -147,18 +102,9 @@ static void add_tools(yyjson_mut_doc *doc, yyjson_mut_val *root, const cage_cont
147102 yyjson_mut_val *decls = yyjson_mut_arr(doc);
148103 yyjson_mut_obj_add_val(doc, group, "functionDeclarations", decls);
149104 for (size_t i = 0; i < ctx->tools_len; i++) {
150- const cage_tool *t = &ctx->tools[i];
151105 yyjson_mut_val *d = yyjson_mut_obj(doc);
152106 yyjson_mut_arr_add_val(decls, d);
153- yyjson_mut_obj_add_strcpy(doc, d, "name", t->name);
154- yyjson_mut_obj_add_strcpy(doc, d, "description", t->description ? t->description : "");
155- const char *params = t->parameters ? t->parameters : "{}";
156- yyjson_doc *pdoc = yyjson_read(params, strlen(params), 0);
157- if (pdoc) {
158- yyjson_mut_val *copy = yyjson_val_mut_copy(doc, yyjson_doc_get_root(pdoc));
159- yyjson_mut_obj_add_val(doc, d, "parametersJsonSchema", copy);
160- yyjson_doc_free(pdoc);
161- }
107+ cage_json_tool(doc, d, &ctx->tools[i], "parametersJsonSchema");
162108 }
163109 }
164110
@@ -229,12 +175,12 @@ static char *build_request(const cage_context *ctx, const cage_stream_opts *opts
229175 typedef struct {
230176 char *id;
231177 char *name;
232- buf args;
178+ cage_buf args;
233179 } gcall;
234180
235181 typedef struct {
236- buf text;
237- buf reasoning;
182+ cage_buf text;
183+ cage_buf reasoning;
238184 gcall *calls;
239185 size_t calls_len;
240186 long tokens_in;
@@ -246,12 +192,6 @@ typedef struct {
246192 void *user;
247193 } google_state;
248194
249-static void emit_delta(google_state *st, cage_stream_type type, const char *delta) {
250- if (!st->emit) return;
251- cage_stream_event ev = {.type = type, .delta = delta};
252- st->emit(&ev, st->user);
253-}
254-
255195 static void add_call(google_state *st, const char *name, yyjson_val *args) {
256196 st->calls = realloc(st->calls, (st->calls_len + 1) * sizeof *st->calls);
257197 if (!st->calls) abort();
@@ -271,7 +211,8 @@ static void add_call(google_state *st, const char *name, yyjson_val *args) {
271211 }
272212 }
273213
274-static void handle_chunk(google_state *st, const char *json, size_t len) {
214+static void on_data(const char *json, size_t len, void *user) {
215+ google_state *st = user;
275216 yyjson_doc *doc = yyjson_read(json, len, 0);
276217 if (!doc) {
277218 if (!st->error) st->error = xstrdup("stream: invalid JSON chunk");
@@ -309,10 +250,10 @@ static void handle_chunk(google_state *st, const char *json, size_t len) {
309250 const char *s = yyjson_get_str(txt);
310251 if (yyjson_is_bool(thought) && yyjson_get_bool(thought)) {
311252 buf_add(&st->reasoning, s, strlen(s));
312- emit_delta(st, CAGE_STREAM_REASONING_DELTA, s);
253+ cage_emit_delta(st->emit, st->user, CAGE_STREAM_REASONING_DELTA, s);
313254 } else {
314255 buf_add(&st->text, s, strlen(s));
315- emit_delta(st, CAGE_STREAM_TEXT_DELTA, s);
256+ cage_emit_delta(st->emit, st->user, CAGE_STREAM_TEXT_DELTA, s);
316257 }
317258 }
318259 }
@@ -334,10 +275,6 @@ static void handle_chunk(google_state *st, const char *json, size_t len) {
334275 yyjson_doc_free(doc);
335276 }
336277
337-static void on_data(const char *json, size_t len, void *user) {
338- handle_chunk(user, json, len);
339-}
340-
341278 static void free_state(google_state *st) {
342279 free(st->text.data);
343280 free(st->reasoning.data);
@@ -352,29 +289,11 @@ static void free_state(google_state *st) {
352289 }
353290
354291 static void finalize(google_state *st, cage_message *out) {
355- if (st->reasoning.len > 0) {
356- cage_block *b = cage_message_add_block(out, CAGE_BLOCK_THINKING);
357- b->text = xstrdup(st->reasoning.data);
358- }
359- if (st->text.len > 0) {
360- cage_block *b = cage_message_add_block(out, CAGE_BLOCK_TEXT);
361- b->text = xstrdup(st->text.data);
362- }
292+ cage_add_text_block(out, CAGE_BLOCK_THINKING, st->reasoning.data);
293+ cage_add_text_block(out, CAGE_BLOCK_TEXT, st->text.data);
363294 for (size_t i = 0; i < st->calls_len; i++) {
364295 gcall *c = &st->calls[i];
365- cage_block *b = cage_message_add_block(out, CAGE_BLOCK_TOOL_CALL);
366- b->tool_call_id = xstrdup(c->id);
367- b->tool_name = xstrdup(c->name);
368- b->arguments = xstrdup(c->args.len ? c->args.data : "{}");
369- if (st->emit) {
370- cage_stream_event ev = {
371- .type = CAGE_STREAM_TOOL_CALL,
372- .tool_call_id = b->tool_call_id,
373- .tool_name = b->tool_name,
374- .tool_arguments = b->arguments,
375- };
376- st->emit(&ev, st->user);
377- }
296+ cage_add_tool_block(out, c->id, c->name, c->args.len ? c->args.data : NULL, st->emit, st->user);
378297 }
379298 out->tokens_in = st->tokens_in;
380299 out->tokens_out = st->tokens_out;
@@ -415,57 +334,31 @@ int cage_google_generative_ai_stream(const cage_model *model, const cage_context
415334 out->role = CAGE_ROLE_ASSISTANT;
416335
417336 char *url = endpoint_url(model->base_url, model->model);
418- if (!url) return fail(err, "provider: no base url");
337+ if (!url) return cage_fail(err, "provider: no base url");
419338 char *body = build_request(ctx, opts);
420339 if (!body) {
421340 free(url);
422- return fail(err, "provider: cannot build request");
341+ return cage_fail(err, "provider: cannot build request");
423342 }
424343
425344 google_state st = {0};
426345 st.emit = emit;
427346 st.user = user;
428347
429- char *auth = NULL;
430- struct curl_slist *headers = NULL;
431- headers = curl_slist_append(headers, "Content-Type: application/json");
432- headers = curl_slist_append(headers, "Accept: text/event-stream");
433- if (model->api_key && model->api_key[0]) {
434- size_t n = strlen(model->api_key) + 20;
435- auth = xmalloc(n);
436- snprintf(auth, n, "x-goog-api-key: %s", model->api_key);
437- headers = curl_slist_append(headers, auth);
438- }
439-
440- cage_http_request req = {
441- .url = url,
442- .body = body,
443- .headers = headers,
444- .cancel = cancel,
445- .on_data = on_data,
446- .user = &st,
447- };
448- cage_http_stream(&req);
348+ cage_api_result r = cage_api_post(url, body, "x-goog-api-key: ", model->api_key,
349+ NULL, cancel, on_data, &st, st.error, err);
449350
450351 int rc = 0;
451- if (req.aborted) {
352+ if (r == CAGE_API_ABORTED) {
452353 out->stop_reason = xstrdup("aborted");
453- } else if (req.error) {
454- *err = req.error;
455- req.error = NULL;
354+ } else if (r == CAGE_API_TRANSPORT_ERROR) {
456355 rc = -1;
457- } else if (st.error) {
356+ } else if (r == CAGE_API_STREAM_ERROR) {
458357 out->stop_reason = xstrdup("error");
459358 out->error_message = xstrdup(st.error);
460359 } else {
461360 finalize(&st, out);
462361 }
463-
464- curl_slist_free_all(headers);
465- free(auth);
466- free(req.error);
467- free(url);
468- free(body);
469362 free_state(&st);
470363 return rc;
471364 }
src/api/http.c+53−25
@@ -1,6 +1,5 @@
11 #include "http.h"
22
3-#include <stdarg.h>
43 #include <stdio.h>
54 #include <stdlib.h>
65 #include <string.h>
@@ -8,29 +7,7 @@
87 #include <yyjson.h>
98
109 #include "sse.h"
11-
12-static void *xmalloc(size_t n) {
13- void *p = malloc(n);
14- if (!p) abort();
15- return p;
16-}
17-
18-static char *xstrdup(const char *s) {
19- size_t n = strlen(s) + 1;
20- char *p = xmalloc(n);
21- memcpy(p, s, n);
22- return p;
23-}
24-
25-static void set_error(char **err, const char *fmt, ...) {
26- char detail[512];
27- va_list ap;
28- va_start(ap, fmt);
29- vsnprintf(detail, sizeof detail, fmt, ap);
30- va_end(ap);
31- free(*err);
32- *err = xstrdup(detail);
33-}
10+#include "util.h"
3411
3512 typedef struct {
3613 cage_sse sse;
@@ -145,7 +122,7 @@ int cage_http_stream(cage_http_request *req) {
145122 if (req->aborted) {
146123 // The caller turns this into an "aborted" stop reason.
147124 } else if (res != CURLE_OK) {
148- set_error(&req->error, "provider: %s", curl_easy_strerror(res));
125+ cage_set_error(&req->error, "provider: %s", curl_easy_strerror(res));
149126 rc = -1;
150127 } else if (st.status >= 400) {
151128 req->error = http_error(st.status, st.raw, st.raw_len);
@@ -155,3 +132,54 @@ int cage_http_stream(cage_http_request *req) {
155132 free(st.raw);
156133 return rc;
157134 }
135+
136+cage_api_result cage_api_post(const char *url, const char *body,
137+ const char *auth_prefix, const char *api_key,
138+ const char *const *extra,
139+ const volatile bool *cancel,
140+ cage_http_data_fn on_data, void *user,
141+ const char *stream_error, char **err) {
142+ struct curl_slist *headers = NULL;
143+ headers = curl_slist_append(headers, "Content-Type: application/json");
144+ headers = curl_slist_append(headers, "Accept: text/event-stream");
145+ char *auth = NULL;
146+ if (auth_prefix && api_key && api_key[0]) {
147+ size_t n = strlen(auth_prefix) + strlen(api_key) + 1;
148+ auth = xmalloc(n);
149+ snprintf(auth, n, "%s%s", auth_prefix, api_key);
150+ headers = curl_slist_append(headers, auth);
151+ }
152+ for (size_t i = 0; extra && extra[i]; i++)
153+ headers = curl_slist_append(headers, extra[i]);
154+
155+ cage_http_request req = {
156+ .url = url,
157+ .body = body,
158+ .headers = headers,
159+ .cancel = cancel,
160+ .on_data = on_data,
161+ .user = user,
162+ };
163+ cage_http_stream(&req);
164+
165+ cage_api_result result;
166+ if (req.aborted) {
167+ result = CAGE_API_ABORTED;
168+ } else if (req.error) {
169+ free(*err);
170+ *err = req.error;
171+ req.error = NULL;
172+ result = CAGE_API_TRANSPORT_ERROR;
173+ } else if (stream_error) {
174+ result = CAGE_API_STREAM_ERROR;
175+ } else {
176+ result = CAGE_API_OK;
177+ }
178+
179+ curl_slist_free_all(headers);
180+ free(auth);
181+ free(req.error);
182+ free((char *)url);
183+ free((char *)body);
184+ return result;
185+}
src/api/http.h+18−0
@@ -33,4 +33,22 @@ typedef struct {
3333 // set).
3434 int cage_http_stream(cage_http_request *req);
3535
36+typedef enum {
37+ CAGE_API_OK, // the caller should finalize
38+ CAGE_API_ABORTED, // the cancel flag was observed
39+ CAGE_API_STREAM_ERROR, // the stream reported an error (see stream_error)
40+ CAGE_API_TRANSPORT_ERROR, // the transfer failed; *err is set
41+} cage_api_result;
42+
43+// Builds the standard headers (Content-Type, Accept, an optional auth line
44+// "auth_prefix + api_key", and the NULL-terminated `extra` headers) and runs a
45+// streaming POST. `stream_error` is the adapter's recorded stream error, or
46+// NULL. Takes ownership of url and body.
47+cage_api_result cage_api_post(const char *url, const char *body,
48+ const char *auth_prefix, const char *api_key,
49+ const char *const *extra,
50+ const volatile bool *cancel,
51+ cage_http_data_fn on_data, void *user,
52+ const char *stream_error, char **err);
53+
3654 #endif
src/api/openai_completions.c+28−156
@@ -4,7 +4,6 @@
44 #include "api.h"
55
66 #include <curl/curl.h>
7-#include <stdarg.h>
87 #include <stdio.h>
98 #include <stdlib.h>
109 #include <string.h>
@@ -13,69 +12,10 @@
1312
1413 #include "http.h"
1514 #include "sse.h"
16-
17-static void *xmalloc(size_t n) {
18- void *p = malloc(n);
19- if (!p) abort();
20- return p;
21-}
22-
23-static char *xstrdup(const char *s) {
24- size_t n = strlen(s) + 1;
25- char *p = xmalloc(n);
26- memcpy(p, s, n);
27- return p;
28-}
29-
30-static int fail(char **err, const char *fmt, ...) {
31- char detail[512];
32- va_list ap;
33- va_start(ap, fmt);
34- vsnprintf(detail, sizeof detail, fmt, ap);
35- va_end(ap);
36- *err = xstrdup(detail);
37- return -1;
38-}
39-
40-// ---- growable byte buffer -------------------------------------------------
41-
42-typedef struct {
43- char *data;
44- size_t len;
45- size_t cap;
46-} buf;
47-
48-static void buf_add(buf *b, const void *p, size_t n) {
49- if (b->len + n + 1 > b->cap) {
50- size_t cap = b->cap ? b->cap : 128;
51- while (cap < b->len + n + 1) cap *= 2;
52- b->data = realloc(b->data, cap);
53- if (!b->data) abort();
54- b->cap = cap;
55- }
56- memcpy(b->data + b->len, p, n);
57- b->len += n;
58- b->data[b->len] = '\0';
59-}
60-
61-static void buf_free(buf *b) {
62- free(b->data);
63- b->data = NULL;
64- b->len = b->cap = 0;
65-}
15+#include "util.h"
6616
6717 // ---- request building -----------------------------------------------------
6818
69-// Concatenates a message's text blocks into one string.
70-static char *join_text(const cage_message *m) {
71- buf b = {0};
72- for (size_t i = 0; i < m->blocks_len; i++)
73- if (m->blocks[i].type == CAGE_BLOCK_TEXT && m->blocks[i].text)
74- buf_add(&b, m->blocks[i].text, strlen(m->blocks[i].text));
75- buf_add(&b, "", 0);
76- return b.data;
77-}
78-
7919 static void add_message(yyjson_mut_doc *doc, yyjson_mut_val *arr, const cage_message *m) {
8020 yyjson_mut_val *o = yyjson_mut_obj(doc);
8121 yyjson_mut_arr_add_val(arr, o);
@@ -83,7 +23,7 @@ static void add_message(yyjson_mut_doc *doc, yyjson_mut_val *arr, const cage_mes
8323 if (m->role == CAGE_ROLE_TOOL) {
8424 yyjson_mut_obj_add_strcpy(doc, o, "role", "tool");
8525 yyjson_mut_obj_add_strcpy(doc, o, "tool_call_id", m->tool_call_id ? m->tool_call_id : "");
86- char *t = join_text(m);
26+ char *t = cage_message_text(m);
8727 if (t[0] == '\0' && cage_message_has_image(m)) {
8828 free(t);
8929 t = xstrdup("(see attached image)");
@@ -94,14 +34,14 @@ static void add_message(yyjson_mut_doc *doc, yyjson_mut_val *arr, const cage_mes
9434 }
9535 if (m->role == CAGE_ROLE_USER) {
9636 yyjson_mut_obj_add_strcpy(doc, o, "role", "user");
97- char *t = join_text(m);
37+ char *t = cage_message_text(m);
9838 yyjson_mut_obj_add_strcpy(doc, o, "content", t);
9939 free(t);
10040 return;
10141 }
10242
10343 yyjson_mut_obj_add_strcpy(doc, o, "role", "assistant");
104- char *t = join_text(m);
44+ char *t = cage_message_text(m);
10545 yyjson_mut_obj_add_strcpy(doc, o, "content", t);
10646 free(t);
10747
@@ -134,15 +74,7 @@ static void add_tools(yyjson_mut_doc *doc, yyjson_mut_val *root, const cage_cont
13474 yyjson_mut_obj_add_strcpy(doc, tool, "type", "function");
13575 yyjson_mut_val *fn = yyjson_mut_obj(doc);
13676 yyjson_mut_obj_add_val(doc, tool, "function", fn);
137- yyjson_mut_obj_add_strcpy(doc, fn, "name", t->name);
138- yyjson_mut_obj_add_strcpy(doc, fn, "description", t->description ? t->description : "");
139- const char *params = t->parameters ? t->parameters : "{}";
140- yyjson_doc *pdoc = yyjson_read(params, strlen(params), 0);
141- if (pdoc) {
142- yyjson_mut_val *copy = yyjson_val_mut_copy(doc, yyjson_doc_get_root(pdoc));
143- yyjson_mut_obj_add_val(doc, fn, "parameters", copy);
144- yyjson_doc_free(pdoc);
145- }
77+ cage_json_tool(doc, fn, t, "parameters");
14678 }
14779 }
14880
@@ -233,12 +165,12 @@ static char *build_request(const cage_model *model, const cage_context *ctx,
233165 typedef struct {
234166 char *id;
235167 char *name;
236- buf args;
168+ cage_buf args;
237169 } tool_acc;
238170
239171 typedef struct {
240- buf text;
241- buf reasoning;
172+ cage_buf text;
173+ cage_buf reasoning;
242174 tool_acc *calls;
243175 size_t calls_len;
244176 char *finish_reason;
@@ -250,12 +182,6 @@ typedef struct {
250182 void *user;
251183 } sse_state;
252184
253-static void emit_delta(sse_state *st, cage_stream_type type, const char *delta) {
254- if (!st->emit) return;
255- cage_stream_event ev = {.type = type, .delta = delta};
256- st->emit(&ev, st->user);
257-}
258-
259185 static void grow_calls(sse_state *st, size_t count) {
260186 if (count <= st->calls_len) return;
261187 st->calls = realloc(st->calls, count * sizeof *st->calls);
@@ -269,7 +195,7 @@ static void handle_delta(sse_state *st, yyjson_val *delta) {
269195 if (yyjson_is_str(content) && yyjson_get_str(content)[0]) {
270196 const char *s = yyjson_get_str(content);
271197 buf_add(&st->text, s, strlen(s));
272- emit_delta(st, CAGE_STREAM_TEXT_DELTA, s);
198+ cage_emit_delta(st->emit, st->user, CAGE_STREAM_TEXT_DELTA, s);
273199 }
274200
275201 static const char *const reasoning_fields[] = {"reasoning_content", "reasoning", "reasoning_text"};
@@ -278,7 +204,7 @@ static void handle_delta(sse_state *st, yyjson_val *delta) {
278204 if (!yyjson_is_str(r) || !yyjson_get_str(r)[0]) continue;
279205 const char *s = yyjson_get_str(r);
280206 buf_add(&st->reasoning, s, strlen(s));
281- emit_delta(st, CAGE_STREAM_REASONING_DELTA, s);
207+ cage_emit_delta(st->emit, st->user, CAGE_STREAM_REASONING_DELTA, s);
282208 break;
283209 }
284210
@@ -311,7 +237,8 @@ static void handle_delta(sse_state *st, yyjson_val *delta) {
311237 }
312238 }
313239
314-static void handle_data(sse_state *st, const char *json, size_t len) {
240+static void on_data(const char *json, size_t len, void *user) {
241+ sse_state *st = user;
315242 yyjson_doc *doc = yyjson_read(json, len, 0);
316243 if (!doc) {
317244 if (!st->error) st->error = xstrdup("stream: invalid JSON chunk");
@@ -357,10 +284,6 @@ static void handle_data(sse_state *st, const char *json, size_t len) {
Cut short: this commit's diff is over 1000 lines.
src/api/openai_responses.c+30−157
Cut short: this commit's diff is over 1000 lines.
src/config.c+14−84
Cut short: this commit's diff is over 1000 lines.
src/diff.c+13−50
Cut short: this commit's diff is over 1000 lines.
src/main.c+2−18
Cut short: this commit's diff is over 1000 lines.
src/message.c+10−7
Cut short: this commit's diff is over 1000 lines.
src/message.h+3−0
Cut short: this commit's diff is over 1000 lines.
src/provider.c+43−0
Cut short: this commit's diff is over 1000 lines.
src/resolve.c+4−15
Cut short: this commit's diff is over 1000 lines.
src/resources.c+12−79
Cut short: this commit's diff is over 1000 lines.
src/session.c+12−60
Cut short: this commit's diff is over 1000 lines.
src/tool.c+18−52
Cut short: this commit's diff is over 1000 lines.
src/tui/buf.h+0−84
Cut short: this commit's diff is over 1000 lines.
src/tui/commands.c+6−23
Cut short: this commit's diff is over 1000 lines.
src/tui/complete.c+1−1
Cut short: this commit's diff is over 1000 lines.
src/tui/editor.c+55−150
Cut short: this commit's diff is over 1000 lines.
src/tui/editor.h+0−4
Cut short: this commit's diff is over 1000 lines.
src/tui/highlight.c+16−58
Cut short: this commit's diff is over 1000 lines.
src/tui/stream.c+28−79
Cut short: this commit's diff is over 1000 lines.
src/tui/stream.h+12−1
Cut short: this commit's diff is over 1000 lines.
src/tui/term.c+1−1
Cut short: this commit's diff is over 1000 lines.
src/tui/theme.h+1−1
Cut short: this commit's diff is over 1000 lines.
src/tui/tui.c+46−131
Cut short: this commit's diff is over 1000 lines.
src/tui/usage.c+1−1
Cut short: this commit's diff is over 1000 lines.
src/util.c+255−0
Cut short: this commit's diff is over 1000 lines.
src/util.h+82−0
Cut short: this commit's diff is over 1000 lines.
third_party/tree-sitter-json/LICENSE+0−21
Cut short: this commit's diff is over 1000 lines.
third_party/tree-sitter-json/README.md+0−9
Cut short: this commit's diff is over 1000 lines.
third_party/tree-sitter-json/src/parser.c+0−1061
Cut short: this commit's diff is over 1000 lines.
third_party/tree-sitter-json/src/tree_sitter/parser.h+0−266
Cut short: this commit's diff is over 1000 lines.