xonecas.io
7814
Ta

tiny-c-agent / commit 169f275

feat: QuickJS host functions

xonecas2026-10-02 169f275af391745d54d0cefa66e331062ee4688c parent 49e00a8

11 files changed

src/agent.c+8−0
@@ -295,6 +295,14 @@ void cage_agent_turn(cage_agent *a, const char *input) {
295295 cage_tool_result tr = run_tool(a, &st, b);
296296 cage_message tm = cage_message_tool(b->tool_call_id, tr.text, tr.is_error);
297297 free(tr.text);
298+ for (size_t k = 0; k < tr.images_len; k++) {
299+ cage_block *ib = cage_message_add_block(&tm, CAGE_BLOCK_IMAGE);
300+ ib->media_type = xstrdup(tr.images[k].media_type);
301+ ib->data = xstrdup(tr.images[k].data);
302+ free(tr.images[k].media_type);
303+ free(tr.images[k].data);
304+ }
305+ free(tr.images);
298306
299307 if (push_message(a, &tm, &perr) != 0) {
300308 free(held.data);
src/api/openai_completions.c+52−2
@@ -81,6 +81,10 @@ static void add_message(yyjson_mut_doc *doc, yyjson_mut_val *arr, const cage_mes
8181 yyjson_mut_obj_add_strcpy(doc, o, "role", "tool");
8282 yyjson_mut_obj_add_strcpy(doc, o, "tool_call_id", m->tool_call_id ? m->tool_call_id : "");
8383 char *t = join_text(m);
84+ if (t[0] == '\0' && cage_message_has_image(m)) {
85+ free(t);
86+ t = xstrdup("(see attached image)");
87+ }
8488 yyjson_mut_obj_add_strcpy(doc, o, "content", t);
8589 free(t);
8690 return;
@@ -164,8 +168,54 @@ static char *build_request(const cage_model *model, const cage_context *ctx,
164168 yyjson_mut_obj_add_strcpy(doc, sys, "role", "system");
165169 yyjson_mut_obj_add_strcpy(doc, sys, "content", ctx->system_prompt);
166170 }
167- for (size_t i = 0; i < ctx->messages_len; i++)
168- add_message(doc, messages, &ctx->messages[i]);
171+ for (size_t i = 0; i < ctx->messages_len; ) {
172+ if (ctx->messages[i].role == CAGE_ROLE_TOOL) {
173+ // A run of tool results lands together. Any images among them are
174+ // sent as one following user message, because a tool message's
175+ // content is a string and the provider rejects a user message
176+ // between a call and its results.
177+ size_t j = i;
178+ bool has_images = false;
179+ for (; j < ctx->messages_len && ctx->messages[j].role == CAGE_ROLE_TOOL; j++) {
180+ add_message(doc, messages, &ctx->messages[j]);
181+ if (cage_message_has_image(&ctx->messages[j])) has_images = true;
182+ }
183+ if (has_images) {
184+ yyjson_mut_val *um = yyjson_mut_obj(doc);
185+ yyjson_mut_arr_add_val(messages, um);
186+ yyjson_mut_obj_add_strcpy(doc, um, "role", "user");
187+ yyjson_mut_val *content = yyjson_mut_arr(doc);
188+ yyjson_mut_obj_add_val(doc, um, "content", content);
189+ yyjson_mut_val *head = yyjson_mut_obj(doc);
190+ yyjson_mut_arr_add_val(content, head);
191+ yyjson_mut_obj_add_strcpy(doc, head, "type", "text");
192+ yyjson_mut_obj_add_strcpy(doc, head, "text", "Attached image(s) from tool result:");
193+ for (size_t m = i; m < j; m++) {
194+ const cage_message *msg = &ctx->messages[m];
195+ for (size_t k = 0; k < msg->blocks_len; k++) {
196+ const cage_block *b = &msg->blocks[k];
197+ if (b->type != CAGE_BLOCK_IMAGE) continue;
198+ yyjson_mut_val *iu = yyjson_mut_obj(doc);
199+ yyjson_mut_arr_add_val(content, iu);
200+ yyjson_mut_obj_add_strcpy(doc, iu, "type", "image_url");
201+ yyjson_mut_val *url = yyjson_mut_obj(doc);
202+ yyjson_mut_obj_add_val(doc, iu, "image_url", url);
203+ const char *mt = b->media_type ? b->media_type : "";
204+ const char *bs = b->data ? b->data : "";
205+ size_t need = strlen(mt) + strlen(bs) + 32;
206+ char *u = xmalloc(need);
207+ snprintf(u, need, "data:%s;base64,%s", mt, bs);
208+ yyjson_mut_obj_add_strcpy(doc, url, "url", u);
209+ free(u);
210+ }
211+ }
212+ }
213+ i = j;
214+ } else {
215+ add_message(doc, messages, &ctx->messages[i]);
216+ i++;
217+ }
218+ }
169219
170220 add_tools(doc, root, ctx);
171221
src/codemode.c+60−11
@@ -22,6 +22,9 @@ struct cage_runtime {
2222 cage_tool_output_fn out;
2323 void *out_user;
2424 const volatile bool *cancel;
25+ bool supports_images;
26+ cage_image *images; // attached during a run, moved to the result
27+ size_t images_len;
2528 };
2629
2730 // ---- small helpers --------------------------------------------------------
@@ -170,19 +173,27 @@ static JSValue js_host(JSContext *ctx, JSValueConst this_val, int argc,
170173 const char *cargs = JS_ToCString(ctx, jargs);
171174 JS_FreeValue(ctx, jargs);
172175
173- char *result = h->fn(cargs ? cargs : "[]", h->user);
176+ cage_host_result result = h->fn(cargs ? cargs : "[]", h->user);
174177 JS_FreeCString(ctx, cargs);
175- if (!result) return JS_NULL;
176178
177- JSValue parsed = JS_ParseJSON(ctx, result, strlen(result), "<host>");
178- free(result);
179+ if (result.error) {
180+ free(result.json);
181+ JSValue exc = JS_ThrowPlainError(ctx, "%s", result.error);
182+ free(result.error);
183+ return exc;
184+ }
185+ if (!result.json) return JS_NULL;
186+
187+ JSValue parsed = JS_ParseJSON(ctx, result.json, strlen(result.json), "<host>");
188+ free(result.json);
179189 return parsed;
180190 }
181191
182-cage_runtime *cage_runtime_new(void) {
192+cage_runtime *cage_runtime_new(bool supports_images) {
183193 cage_runtime *r = xcalloc(1, sizeof *r);
184194 r->rt = JS_NewRuntime();
185195 r->ctx = JS_NewContext(r->rt);
196+ r->supports_images = supports_images;
186197 JS_SetContextOpaque(r->ctx, r);
187198 JS_SetInterruptHandler(r->rt, on_interrupt, r);
188199
@@ -208,10 +219,36 @@ void cage_runtime_register(cage_runtime *r, const char *name, cage_host_fn fn, v
208219 JS_FreeValue(r->ctx, global);
209220 }
210221
222+void cage_runtime_output(cage_runtime *r, const char *chunk) {
223+ if (r->out) r->out(chunk, r->out_user);
224+}
225+
226+void cage_runtime_add_image(cage_runtime *r, const char *media_type, const char *base64) {
227+ r->images = realloc(r->images, (r->images_len + 1) * sizeof *r->images);
228+ if (!r->images) abort();
229+ r->images[r->images_len++] = (cage_image){
230+ .media_type = xstrdup(media_type),
231+ .data = xstrdup(base64),
232+ };
233+}
234+
235+bool cage_runtime_supports_images(const cage_runtime *r) {
236+ return r->supports_images;
237+}
238+
239+bool cage_runtime_cancelled(const cage_runtime *r) {
240+ return r->cancel && *r->cancel;
241+}
242+
211243 void cage_runtime_free(cage_runtime *r) {
212244 if (!r) return;
213245 for (size_t i = 0; i < r->hosts_len; i++) free(r->hosts[i].name);
214246 free(r->hosts);
247+ for (size_t i = 0; i < r->images_len; i++) {
248+ free(r->images[i].media_type);
249+ free(r->images[i].data);
250+ }
251+ free(r->images);
215252 JS_FreeContext(r->ctx);
216253 JS_FreeRuntime(r->rt);
217254 free(r);
@@ -224,6 +261,8 @@ cage_tool_result cage_runtime_run(cage_runtime *r, const char *script,
224261 r->out = out;
225262 r->out_user = out_user;
226263 r->cancel = cancel;
264+ r->images = NULL;
265+ r->images_len = 0;
227266
228267 const char *pre = "(async () => {\n";
229268 const char *post = "\n})()";
@@ -238,16 +277,17 @@ cage_tool_result cage_runtime_run(cage_runtime *r, const char *script,
238277
239278 if (cancel && *cancel) {
240279 if (JS_IsException(fn)) JS_FreeValue(r->ctx, JS_GetException(r->ctx));
280+ else JS_FreeValue(r->ctx, fn);
241281 res.text = xstrdup("codemode: aborted");
242282 res.is_error = true;
243- return res;
283+ goto done;
244284 }
245285 if (JS_IsException(fn)) {
246286 JSValue e = JS_GetException(r->ctx);
247287 res.text = error_text(r->ctx, e);
248288 res.is_error = true;
249289 JS_FreeValue(r->ctx, e);
250- return res;
290+ goto done;
251291 }
252292
253293 JSContext *jc;
@@ -257,7 +297,7 @@ cage_tool_result cage_runtime_run(cage_runtime *r, const char *script,
257297 JS_FreeValue(r->ctx, fn);
258298 res.text = xstrdup("codemode: aborted");
259299 res.is_error = true;
260- return res;
300+ goto done;
261301 }
262302
263303 switch (JS_PromiseState(r->ctx, fn)) {
@@ -280,6 +320,12 @@ cage_tool_result cage_runtime_run(cage_runtime *r, const char *script,
280320 break;
281321 }
282322 JS_FreeValue(r->ctx, fn);
323+
324+done:
325+ res.images = r->images;
326+ res.images_len = r->images_len;
327+ r->images = NULL;
328+ r->images_len = 0;
283329 return res;
284330 }
285331
@@ -287,9 +333,12 @@ cage_tool cage_codemode_tool(void) {
287333 cage_tool t = {
288334 .name = "codemode",
289335 .description =
290- "Run a JavaScript program. The program may use await. Call the "
291- "provided host functions directly as globals, write progress with "
292- "console.log, and return the value to report back as the result.",
336+ "Run a JavaScript program. The program may use await. The globals "
337+ "are: read(path) returns a file's text; edit(path, oldText, newText) "
338+ "replaces the single occurrence of oldText in a file (empty oldText "
339+ "creates it); bash(command) runs a shell command and resolves to "
340+ "{ output, exitCode }. Write progress with console.log and return the "
341+ "value to report back as the result.",
293342 .parameters =
294343 "{\"type\":\"object\","
295344 "\"properties\":{\"code\":{\"type\":\"string\",\"description\":\"JavaScript to run\"}},"
src/host.c+541−0
@@ -0,0 +1,541 @@
1+// The read, edit, and bash capabilities, exposed as codemode globals.
2+
3+#include "host.h"
4+
5+#include <errno.h>
6+#include <fcntl.h>
7+#include <poll.h>
8+#include <signal.h>
9+#include <stdarg.h>
10+#include <stdint.h>
11+#include <stdio.h>
12+#include <stdlib.h>
13+#include <string.h>
14+#include <strings.h>
15+#include <sys/stat.h>
16+#include <sys/wait.h>
17+#include <unistd.h>
18+
19+#include <yyjson.h>
20+
21+#define MAX_TEXT 100000
22+#define MAX_IMAGE_B64 (5u * 1024 * 1024)
23+#define MAX_READ (16u * 1024 * 1024)
24+#define MAX_HEAD 10000
25+#define MAX_TAIL 6000
26+#define TRUNCATED "\n\n... output truncated ...\n\n"
27+
28+// ---- small helpers --------------------------------------------------------
29+
30+static void *xmalloc(size_t n) {
31+ void *p = malloc(n);
32+ if (!p) abort();
33+ return p;
34+}
35+
36+static char *xstrdup(const char *s) {
37+ size_t n = strlen(s) + 1;
38+ char *p = xmalloc(n);
39+ memcpy(p, s, n);
40+ return p;
41+}
42+
43+typedef struct {
44+ char *data;
45+ size_t len;
46+ size_t cap;
47+} buf;
48+
49+static void buf_add(buf *b, const char *p, size_t n) {
50+ if (b->len + n + 1 > b->cap) {
51+ size_t cap = b->cap ? b->cap : 64;
52+ while (cap < b->len + n + 1) cap *= 2;
53+ b->data = realloc(b->data, cap);
54+ if (!b->data) abort();
55+ b->cap = cap;
56+ }
57+ memcpy(b->data + b->len, p, n);
58+ b->len += n;
59+ b->data[b->len] = '\0';
60+}
61+
62+static void buf_addz(buf *b, const char *s) {
63+ buf_add(b, s, strlen(s));
64+}
65+
66+static cage_host_result ok_json(char *json) {
67+ return (cage_host_result){.json = json};
68+}
69+
70+static cage_host_result err(const char *fmt, ...) {
71+ char detail[512];
72+ va_list ap;
73+ va_start(ap, fmt);
74+ vsnprintf(detail, sizeof detail, fmt, ap);
75+ va_end(ap);
76+ return (cage_host_result){.error = xstrdup(detail)};
77+}
78+
79+// A JSON string value; `s` must be valid UTF-8 and NUL-terminated.
80+static char *json_string(const char *s) {
81+ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
82+ yyjson_mut_doc_set_root(doc, yyjson_mut_strcpy(doc, s));
83+ char *out = yyjson_mut_write(doc, 0, NULL);
84+ yyjson_mut_doc_free(doc);
85+ return out;
86+}
87+
88+// nth argument of the JSON array the runtime passes to a host function.
89+static yyjson_val *arg_at(yyjson_doc *doc, size_t i) {
90+ if (!doc) return NULL;
91+ yyjson_val *root = yyjson_doc_get_root(doc);
92+ if (!yyjson_is_arr(root)) return NULL;
93+ return yyjson_arr_get(root, i);
94+}
95+
96+// ---- UTF-8 ----------------------------------------------------------------
97+
98+// Validates one sequence at `p` (n bytes remain), returning its length.
99+static bool utf8_seq(const unsigned char *p, size_t n, size_t *len) {
100+ unsigned char c = p[0];
101+ if (c >= 0xC2 && c <= 0xDF) {
102+ if (n >= 2 && (p[1] & 0xC0) == 0x80) return (*len = 2, true);
103+ } else if (c == 0xE0) {
104+ if (n >= 3 && p[1] >= 0xA0 && p[1] <= 0xBF && (p[2] & 0xC0) == 0x80) return (*len = 3, true);
105+ } else if (c >= 0xE1 && c <= 0xEC) {
106+ if (n >= 3 && (p[1] & 0xC0) == 0x80 && (p[2] & 0xC0) == 0x80) return (*len = 3, true);
107+ } else if (c == 0xED) {
108+ if (n >= 3 && p[1] >= 0x80 && p[1] <= 0x9F && (p[2] & 0xC0) == 0x80) return (*len = 3, true);
109+ } else if (c >= 0xEE && c <= 0xEF) {
110+ if (n >= 3 && (p[1] & 0xC0) == 0x80 && (p[2] & 0xC0) == 0x80) return (*len = 3, true);
111+ } else if (c == 0xF0) {
112+ if (n >= 4 && p[1] >= 0x90 && p[1] <= 0xBF && (p[2] & 0xC0) == 0x80 && (p[3] & 0xC0) == 0x80)
113+ return (*len = 4, true);
114+ } else if (c >= 0xF1 && c <= 0xF3) {
115+ if (n >= 4 && (p[1] & 0xC0) == 0x80 && (p[2] & 0xC0) == 0x80 && (p[3] & 0xC0) == 0x80)
116+ return (*len = 4, true);
117+ } else if (c == 0xF4) {
118+ if (n >= 4 && p[1] >= 0x80 && p[1] <= 0x8F && (p[2] & 0xC0) == 0x80 && (p[3] & 0xC0) == 0x80)
119+ return (*len = 4, true);
120+ }
121+ return false;
122+}
123+
124+// Replaces invalid byte sequences with U+FFFD, so the text survives the JSON
125+// and session round trips. Mirrors a UTF-8 decode with replacement.
126+static char *utf8_clean(const char *in, size_t n) {
127+ buf b = {0};
128+ const unsigned char *p = (const unsigned char *)in;
129+ size_t i = 0;
130+ while (i < n) {
131+ size_t len;
132+ if (p[i] < 0x80) {
133+ buf_add(&b, (const char *)&p[i], 1);
134+ i += 1;
135+ } else if (utf8_seq(p + i, n - i, &len)) {
136+ buf_add(&b, (const char *)(p + i), len);
137+ i += len;
138+ } else {
139+ buf_add(&b, "\xef\xbf\xbd", 3);
140+ i += 1;
141+ }
142+ }
143+ if (!b.data) buf_add(&b, "", 1);
144+ return b.data;
145+}
146+
147+// ---- file helpers ---------------------------------------------------------
148+
149+// Reads up to MAX_READ bytes. Returns 0, or -1 with errno set.
150+static int slurp(const char *path, buf *out) {
151+ int fd = open(path, O_RDONLY);
152+ if (fd < 0) return -1;
153+ struct stat st;
154+ if (fstat(fd, &st) != 0) {
155+ int e = errno;
156+ close(fd);
157+ errno = e;
158+ return -1;
159+ }
160+ if (S_ISDIR(st.st_mode)) {
161+ close(fd);
162+ errno = EISDIR;
163+ return -1;
164+ }
165+ for (;;) {
166+ if (out->len >= MAX_READ) break;
167+ char tmp[65536];
168+ size_t want = sizeof tmp;
169+ if (out->len + want > MAX_READ) want = MAX_READ - out->len;
170+ ssize_t n = read(fd, tmp, want);
171+ if (n < 0) {
172+ if (errno == EINTR) continue;
173+ int e = errno;
174+ close(fd);
175+ errno = e;
176+ return -1;
177+ }
178+ if (n == 0) break;
179+ buf_add(out, tmp, (size_t)n);
180+ }
181+ close(fd);
182+ return 0;
183+}
184+
185+static int spill(const char *path, const char *data, size_t len) {
186+ int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
187+ if (fd < 0) return -1;
188+ size_t off = 0;
189+ while (off < len) {
190+ ssize_t n = write(fd, data + off, len - off);
191+ if (n < 0) {
192+ if (errno == EINTR) continue;
193+ int e = errno;
194+ close(fd);
195+ errno = e;
196+ return -1;
197+ }
198+ off += (size_t)n;
199+ }
200+ if (close(fd) != 0) return -1;
201+ return 0;
202+}
203+
204+static bool find_sub(const char *hay, size_t hlen, const char *needle, size_t nlen, size_t *at) {
205+ if (nlen == 0 || nlen > hlen) return false;
206+ for (size_t i = 0; i + nlen <= hlen; i++) {
207+ if (hay[i] == needle[0] && memcmp(hay + i, needle, nlen) == 0) {
208+ *at = i;
209+ return true;
210+ }
211+ }
212+ return false;
213+}
214+
215+static char *base64_encode(const unsigned char *data, size_t len) {
216+ static const char table[] =
217+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
218+ char *out = xmalloc(4 * ((len + 2) / 3) + 1);
219+ size_t i = 0, o = 0;
220+ for (; i + 3 <= len; i += 3) {
221+ uint32_t v = (uint32_t)data[i] << 16 | (uint32_t)data[i + 1] << 8 | data[i + 2];
222+ out[o++] = table[(v >> 18) & 63];
223+ out[o++] = table[(v >> 12) & 63];
224+ out[o++] = table[(v >> 6) & 63];
225+ out[o++] = table[v & 63];
226+ }
227+ if (len - i == 1) {
228+ uint32_t v = (uint32_t)data[i] << 16;
229+ out[o++] = table[(v >> 18) & 63];
230+ out[o++] = table[(v >> 12) & 63];
231+ out[o++] = '=';
232+ out[o++] = '=';
233+ } else if (len - i == 2) {
234+ uint32_t v = (uint32_t)data[i] << 16 | (uint32_t)data[i + 1] << 8;
235+ out[o++] = table[(v >> 18) & 63];
236+ out[o++] = table[(v >> 12) & 63];
237+ out[o++] = table[(v >> 6) & 63];
238+ out[o++] = '=';
239+ }
240+ out[o] = '\0';
241+ return out;
242+}
243+
244+static const char *image_mime(const char *path) {
245+ const char *dot = strrchr(path, '.');
246+ if (!dot) return NULL;
247+ const char *e = dot + 1;
248+ if (strcasecmp(e, "png") == 0) return "image/png";
249+ if (strcasecmp(e, "jpg") == 0 || strcasecmp(e, "jpeg") == 0) return "image/jpeg";
250+ if (strcasecmp(e, "webp") == 0) return "image/webp";
251+ return NULL;
252+}
253+
254+// ---- read -----------------------------------------------------------------
255+
256+static cage_host_result host_read(const char *args_json, void *user) {
257+ cage_runtime *rt = user;
258+ yyjson_doc *doc = yyjson_read(args_json, strlen(args_json), 0);
259+ yyjson_val *a = arg_at(doc, 0);
260+ if (!yyjson_is_str(a)) {
261+ yyjson_doc_free(doc);
262+ return err("read: path must be a string");
263+ }
264+ const char *path = yyjson_get_str(a);
265+
266+ buf data = {0};
267+ if (slurp(path, &data) != 0) {
268+ cage_host_result r = err("read failed: %s: %s", path, strerror(errno));
269+ free(data.data);
270+ yyjson_doc_free(doc);
271+ return r;
272+ }
273+
274+ const char *mime = image_mime(path);
275+ if (mime) {
276+ if (!cage_runtime_supports_images(rt)) {
277+ cage_host_result r = err("read failed: %s is an image and the current model does not accept image input", path);
278+ free(data.data);
279+ yyjson_doc_free(doc);
280+ return r;
281+ }
282+ char *b64 = base64_encode((const unsigned char *)data.data, data.len);
283+ if (strlen(b64) > MAX_IMAGE_B64) {
284+ cage_host_result r = err("read failed: %s encodes to %zu bytes, over the %u byte image limit",
285+ path, strlen(b64), MAX_IMAGE_B64);
286+ free(b64);
287+ free(data.data);
288+ yyjson_doc_free(doc);
289+ return r;
290+ }
291+ char msg[1024];
292+ snprintf(msg, sizeof msg, "read %s (%s, %zu bytes)", path, mime, data.len);
293+ cage_runtime_add_image(rt, mime, b64);
294+ free(b64);
295+ free(data.data);
296+ yyjson_doc_free(doc);
297+ return ok_json(json_string(msg));
298+ }
299+
300+ size_t sniff = data.len < 8000 ? data.len : 8000;
301+ if (sniff > 0 && memchr(data.data, 0, sniff)) {
302+ cage_host_result r = err("read failed: %s is binary; use bash (file, xxd)", path);
303+ free(data.data);
304+ yyjson_doc_free(doc);
305+ return r;
306+ }
307+
308+ size_t take = data.len > MAX_TEXT ? MAX_TEXT : data.len;
309+ char *clean = utf8_clean(data.data ? data.data : "", take);
310+ if (data.len > MAX_TEXT) {
311+ buf out = {0};
312+ buf_addz(&out, clean);
313+ char marker[256];
314+ snprintf(marker, sizeof marker, "\n\n... truncated ... %s is %zu characters\n", path, data.len);
315+ buf_addz(&out, marker);
316+ free(clean);
317+ clean = out.data;
318+ }
319+ free(data.data);
320+ yyjson_doc_free(doc);
321+ return ok_json(json_string(clean));
322+}
323+
324+// ---- edit -----------------------------------------------------------------
325+
326+static cage_host_result host_edit(const char *args_json, void *user) {
327+ (void)user;
328+ yyjson_doc *doc = yyjson_read(args_json, strlen(args_json), 0);
329+ yyjson_val *pa = arg_at(doc, 0), *oa = arg_at(doc, 1), *na = arg_at(doc, 2);
330+ if (!yyjson_is_str(pa) || !yyjson_is_str(oa) || !yyjson_is_str(na)) {
331+ yyjson_doc_free(doc);
332+ return err("edit: path, oldText and newText must be strings");
333+ }
334+ const char *path = yyjson_get_str(pa);
335+ const char *old = yyjson_get_str(oa);
336+ size_t old_len = yyjson_get_len(oa);
337+ const char *nw = yyjson_get_str(na);
338+ size_t new_len = yyjson_get_len(na);
339+
340+ if (old_len == 0) {
341+ if (access(path, F_OK) == 0) {
342+ cage_host_result r = err("edit failed: %s already exists", path);
343+ yyjson_doc_free(doc);
344+ return r;
345+ }
346+ if (spill(path, nw, new_len) != 0) {
347+ cage_host_result r = err("edit failed: %s: %s", path, strerror(errno));
348+ yyjson_doc_free(doc);
349+ return r;
350+ }
351+ char msg[1024];
352+ snprintf(msg, sizeof msg, "created %s", path);
353+ yyjson_doc_free(doc);
354+ return ok_json(json_string(msg));
355+ }
356+
357+ buf data = {0};
358+ if (slurp(path, &data) != 0) {
359+ cage_host_result r = err("edit failed: %s: %s", path, strerror(errno));
360+ free(data.data);
361+ yyjson_doc_free(doc);
362+ return r;
363+ }
364+
365+ size_t at;
366+ if (!find_sub(data.data, data.len, old, old_len, &at)) {
367+ cage_host_result r = err("edit failed: oldText not found in %s", path);
368+ free(data.data);
369+ yyjson_doc_free(doc);
370+ return r;
371+ }
372+ size_t second;
373+ if (find_sub(data.data + at + 1, data.len - at - 1, old, old_len, &second)) {
374+ cage_host_result r = err("edit failed: oldText matches more than once in %s", path);
375+ free(data.data);
376+ yyjson_doc_free(doc);
377+ return r;
378+ }
379+
380+ buf out = {0};
381+ buf_add(&out, data.data, at);
382+ buf_add(&out, nw, new_len);
383+ buf_add(&out, data.data + at + old_len, data.len - at - old_len);
384+ if (spill(path, out.data, out.len) != 0) {
385+ cage_host_result r = err("edit failed: %s: %s", path, strerror(errno));
386+ free(out.data);
387+ free(data.data);
388+ yyjson_doc_free(doc);
389+ return r;
390+ }
391+
392+ char msg[1024];
393+ snprintf(msg, sizeof msg, "edited %s", path);
394+ free(out.data);
395+ free(data.data);
396+ yyjson_doc_free(doc);
397+ return ok_json(json_string(msg));
398+}
399+
400+// ---- bash -----------------------------------------------------------------
401+
402+// Keeps only the last MAX_TAIL bytes, flagging that a gap was dropped.
403+static void keep_tail(buf *t, bool *truncated) {
404+ if (t->len <= MAX_TAIL) return;
405+ memmove(t->data, t->data + t->len - MAX_TAIL, MAX_TAIL);
406+ t->len = MAX_TAIL;
407+ t->data[t->len] = '\0';
408+ *truncated = true;
409+}
410+
411+static cage_host_result host_bash(const char *args_json, void *user) {
412+ cage_runtime *rt = user;
413+ yyjson_doc *doc = yyjson_read(args_json, strlen(args_json), 0);
414+ yyjson_val *a = arg_at(doc, 0);
415+ if (!yyjson_is_str(a)) {
416+ yyjson_doc_free(doc);
417+ return err("bash: command must be a string");
418+ }
419+ const char *command = yyjson_get_str(a);
420+
421+ int pipefd[2];
422+ if (pipe(pipefd) != 0) {
423+ cage_host_result r = err("bash: %s", strerror(errno));
424+ yyjson_doc_free(doc);
425+ return r;
426+ }
427+ pid_t pid = fork();
428+ if (pid < 0) {
429+ close(pipefd[0]);
430+ close(pipefd[1]);
431+ cage_host_result r = err("bash: fork: %s", strerror(errno));
432+ yyjson_doc_free(doc);
433+ return r;
434+ }
435+ if (pid == 0) {
436+ setpgid(0, 0);
437+ if (dup2(pipefd[1], STDOUT_FILENO) < 0 || dup2(pipefd[1], STDERR_FILENO) < 0) _exit(127);
438+ close(pipefd[0]);
439+ close(pipefd[1]);
440+ int devnull = open("/dev/null", O_RDONLY);
441+ if (devnull >= 0) {
442+ dup2(devnull, STDIN_FILENO);
443+ close(devnull);
444+ }
445+ execlp("bash", "bash", "-c", command, (char *)NULL);
446+ _exit(127);
447+ }
448+ close(pipefd[1]);
449+ setpgid(pid, pid);
450+
451+ buf head = {0}, tail = {0};
452+ bool truncated = false;
453+ bool cancelled = false;
454+
455+ char chunk[8192];
456+ for (;;) {
457+ if (cage_runtime_cancelled(rt)) {
458+ cancelled = true;
459+ break;
460+ }
461+ struct pollfd pfd = {.fd = pipefd[0], .events = POLLIN};
462+ int pr = poll(&pfd, 1, 100);
463+ if (pr < 0) {
464+ if (errno == EINTR) continue;
465+ break;
466+ }
467+ if (pr == 0) continue;
468+ ssize_t n = read(pipefd[0], chunk, sizeof chunk);
469+ if (n < 0) {
470+ if (errno == EINTR) continue;
471+ break;
472+ }
473+ if (n == 0) break;
474+ chunk[n] = '\0';
475+ cage_runtime_output(rt, chunk);
476+ if (head.len < MAX_HEAD) {
477+ size_t take = MAX_HEAD - head.len;
478+ if ((size_t)n < take) take = (size_t)n;
479+ buf_add(&head, chunk, take);
480+ if (take < (size_t)n) {
481+ buf_add(&tail, chunk + take, (size_t)n - take);
482+ keep_tail(&tail, &truncated);
483+ }
484+ } else {
485+ buf_add(&tail, chunk, (size_t)n);
486+ keep_tail(&tail, &truncated);
487+ }
488+ }
489+ close(pipefd[0]);
490+
491+ int status = 0;
492+ if (cancelled) {
493+ kill(-pid, SIGTERM);
494+ bool reaped = false;
495+ for (int i = 0; i < 30; i++) {
496+ if (waitpid(pid, &status, WNOHANG) == pid) {
497+ reaped = true;
498+ break;
499+ }
500+ usleep(100000);
501+ }
502+ if (!reaped) {
503+ kill(-pid, SIGKILL);
504+ while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {}
505+ }
506+ } else {
507+ while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {}
508+ }
509+
510+ int code;
511+ if (cancelled) code = 143;
512+ else if (WIFEXITED(status)) code = WEXITSTATUS(status);
513+ else if (WIFSIGNALED(status)) code = 128 + WTERMSIG(status);
514+ else code = 0;
515+
516+ buf body = {0};
517+ buf_add(&body, head.data ? head.data : "", head.len);
518+ if (truncated) buf_addz(&body, TRUNCATED);
519+ buf_add(&body, tail.data ? tail.data : "", tail.len);
520+
521+ char *clean = utf8_clean(body.data ? body.data : "", body.len);
522+ yyjson_mut_doc *jd = yyjson_mut_doc_new(NULL);
523+ yyjson_mut_val *o = yyjson_mut_obj(jd);
524+ yyjson_mut_doc_set_root(jd, o);
525+ yyjson_mut_obj_add_strcpy(jd, o, "output", clean);
526+ yyjson_mut_obj_add_int(jd, o, "exitCode", code);
527+ char *json = yyjson_mut_write(jd, 0, NULL);
528+ yyjson_mut_doc_free(jd);
529+ free(clean);
530+ free(body.data);
531+ free(head.data);
532+ free(tail.data);
533+ yyjson_doc_free(doc);
534+ return ok_json(json);
535+}
536+
537+void cage_hosts_register(cage_runtime *rt) {
538+ cage_runtime_register(rt, "read", host_read, rt);
539+ cage_runtime_register(rt, "edit", host_edit, rt);
540+ cage_runtime_register(rt, "bash", host_bash, rt);
541+}
src/host.h+16−0
@@ -0,0 +1,16 @@
1+// cage host functions: read, edit, and bash, exposed as codemode globals.
2+//
3+// They are the seam between a script and its capabilities. `bash` streams its
4+// combined output through the runtime's output callback and honors the run's
5+// cancel flag.
6+
7+#ifndef CAGE_HOST_H
8+#define CAGE_HOST_H
9+
10+#include "tool.h"
11+
12+// Registers read, edit, and bash on the runtime. The runtime outlives the
13+// calls.
14+void cage_hosts_register(cage_runtime *rt);
15+
16+#endif
src/main.c+3−1
@@ -13,6 +13,7 @@
1313 #include "agent.h"
1414 #include "config.h"
1515 #include "headless.h"
16+#include "host.h"
1617 #include "resolve.h"
1718 #include "tool.h"
1819
@@ -130,7 +131,8 @@ int main(int argc, char **argv) {
130131 return 1;
131132 }
132133
133- cage_runtime *runtime = cage_runtime_new();
134+ cage_runtime *runtime = cage_runtime_new(model.supports_images);
135+ cage_hosts_register(runtime);
134136 cage_tool tool = cage_codemode_tool();
135137
136138 signal(SIGINT, on_signal);
src/message.c+13−0
@@ -38,6 +38,12 @@ cage_block *cage_message_add_block(cage_message *m, cage_block_type type) {
3838 return b;
3939 }
4040
41+bool cage_message_has_image(const cage_message *m) {
42+ for (size_t i = 0; i < m->blocks_len; i++)
43+ if (m->blocks[i].type == CAGE_BLOCK_IMAGE) return true;
44+ return false;
45+}
46+
4147 void cage_message_free(cage_message *m) {
4248 if (!m) return;
4349 for (size_t i = 0; i < m->blocks_len; i++) {
@@ -45,6 +51,8 @@ void cage_message_free(cage_message *m) {
4551 free(m->blocks[i].tool_call_id);
4652 free(m->blocks[i].tool_name);
4753 free(m->blocks[i].arguments);
54+ free(m->blocks[i].media_type);
55+ free(m->blocks[i].data);
4856 }
4957 free(m->blocks);
5058 free(m->tool_call_id);
@@ -81,6 +89,11 @@ yyjson_mut_val *cage_message_to_val(yyjson_mut_doc *doc, const cage_message *m)
8189 yyjson_mut_obj_add_strcpy(doc, bo, "name", b->tool_name ? b->tool_name : "");
8290 yyjson_mut_obj_add_strcpy(doc, bo, "arguments", b->arguments ? b->arguments : "{}");
8391 break;
92+ case CAGE_BLOCK_IMAGE:
93+ yyjson_mut_obj_add_strcpy(doc, bo, "type", "image");
94+ yyjson_mut_obj_add_strcpy(doc, bo, "data", b->data ? b->data : "");
95+ yyjson_mut_obj_add_strcpy(doc, bo, "mimeType", b->media_type ? b->media_type : "");
96+ break;
8497 }
8598 }
8699
src/message.h+6−0
@@ -21,6 +21,7 @@ typedef enum {
2121 CAGE_BLOCK_TEXT,
2222 CAGE_BLOCK_THINKING,
2323 CAGE_BLOCK_TOOL_CALL,
24+ CAGE_BLOCK_IMAGE,
2425 } cage_block_type;
2526
2627 typedef struct {
@@ -29,6 +30,8 @@ typedef struct {
2930 char *tool_call_id; // TOOL_CALL
3031 char *tool_name; // TOOL_CALL
3132 char *arguments; // TOOL_CALL, a JSON object string
33+ char *media_type; // IMAGE, e.g. "image/png"
34+ char *data; // IMAGE, base64
3235 } cage_block;
3336
3437 typedef struct {
@@ -50,6 +53,9 @@ cage_message cage_message_tool(const char *tool_call_id, const char *text, bool
5053 // Appends a zeroed block and returns it for the caller to fill.
5154 cage_block *cage_message_add_block(cage_message *m, cage_block_type type);
5255
56+// True when the message carries at least one image block.
57+bool cage_message_has_image(const cage_message *m);
58+
5359 void cage_message_free(cage_message *m);
5460
5561 // Serializes the message to its provider-neutral JSON object.
src/provider.h+3−0
@@ -19,6 +19,9 @@ typedef struct {
1919 const char *base_url; // API root, without the endpoint path
2020 cage_api api;
2121 const char *api_key; // NULL when the endpoint needs no key
22+ // Whether the model accepts image input. Gates whether `read` attaches
23+ // images. The generated catalog will set this per model.
24+ bool supports_images;
2225 // Providers that route by conversation send this header with the session
2326 // id. NULL when the provider does not need one.
2427 const char *session_header;
src/resolve.c+3−0
@@ -27,6 +27,9 @@ int cage_resolve_model(const cage_config *cfg, cage_model *out, char **err) {
2727 memset(out, 0, sizeof *out);
2828 out->provider = cfg->provider;
2929 out->model = cfg->model;
30+ // Model image-input capability is not catalogued yet; assume it. A model
31+ // that rejects images surfaces the provider error as-is.
32+ out->supports_images = true;
3033
3134 if (strcmp(cfg->provider, "opencode-go") == 0) {
3235 out->base_url = "https://opencode.ai/zen/go/v1";
src/tool.h+29−5
@@ -9,32 +9,56 @@
99 #define CAGE_TOOL_H
1010
1111 #include <stdbool.h>
12+#include <stddef.h>
1213
1314 #include "provider.h"
1415
16+// One image a host function attached to the current run.
1517 typedef struct {
16- char *text; // the tool result text; always set
18+ char *media_type; // e.g. "image/png"
19+ char *data; // base64 payload
20+} cage_image;
21+
22+typedef struct {
23+ char *text; // the tool result text; always set
1724 bool is_error;
25+ cage_image *images; // owned by the caller
26+ size_t images_len;
1827 } cage_tool_result;
1928
2029 typedef struct cage_runtime cage_runtime;
2130
2231 typedef void (*cage_tool_output_fn)(const char *chunk, void *user);
2332
33+// A host function's outcome: a JSON value string, or an error to throw. Both
34+// fields are owned by the runtime; `error` wins when set.
35+typedef struct {
36+ char *json; // JSON value text, or NULL for null
37+ char *error; // when set, a JS Error with this message is thrown
38+} cage_host_result;
39+
2440 // A host function callable from the script. `args_json` is a JSON array of the
25-// call arguments; the returned string is the JSON value for the call result
26-// (or NULL for null). The string is owned by the runtime.
27-typedef char *(*cage_host_fn)(const char *args_json, void *user);
41+// call arguments; the returned strings are owned by the runtime.
42+typedef cage_host_result (*cage_host_fn)(const char *args_json, void *user);
2843
2944 // The single tool the model calls.
3045 cage_tool cage_codemode_tool(void);
3146
32-cage_runtime *cage_runtime_new(void);
47+// `supports_images` is the model's image-input capability, used to gate `read`.
48+cage_runtime *cage_runtime_new(bool supports_images);
3349 void cage_runtime_free(cage_runtime *rt);
3450
3551 // Exposes `fn` as a global function named `name` in the runtime.
3652 void cage_runtime_register(cage_runtime *rt, const char *name, cage_host_fn fn, void *user);
3753
54+// Host-side accessors used by the capability implementations. `output` forwards
55+// a chunk to the run's output callback; `add_image` attaches an image to the
56+// run's result.
57+void cage_runtime_output(cage_runtime *rt, const char *chunk);
58+void cage_runtime_add_image(cage_runtime *rt, const char *media_type, const char *base64);
59+bool cage_runtime_supports_images(const cage_runtime *rt);
60+bool cage_runtime_cancelled(const cage_runtime *rt);
61+
3862 // Runs `script` as an async program. Output chunks go to `out`; the program's
3963 // return value becomes the result text. `cancel` is polled by the interpreter
4064 // and may be NULL.