xonecas.io
7814
Ta

tiny-c-agent / commit e87aec3

feat: codemode experiment over

xonecas2026-10-03 e87aec3fe6eedaf3e774c222062b19de6f0c0b1c parent 92e4bbe

14 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.

AGENTS.md+1−1
@@ -30,7 +30,7 @@ A fast, minimal and config first agent for your terminal.
3030 the turn.
3131 - The loop has no compaction, no retries, and no meta-messages between steps.
3232 Provider errors surface as-is, never masked or summarized.
33-- Single codemode-style LLM tool, exectutes the script in a JS environment.
33+- Three LLM tools, matching mini-coder: `read`, `edit`, and `bash`.
3434 - Interruption: ESC politely pauses at the next step boundary; Ctrl+C cancels the
3535 turn (abort the request, kill the tool's process group, persist the aborted
3636 message); Ctrl+C (or CTRL+D) exits on an empty draft. Completed side effects are never
Makefile+1−2
@@ -28,7 +28,7 @@ BASE := -std=$(STD) $(OPT) -pthread
2828
2929 CPPFLAGS += -D_GNU_SOURCE -Isrc -I$(TSJSON)/src -MMD -MP
3030 CFLAGS += $(BASE) $(WARN) $(shell pkg-config --cflags $(PKGS))
31-LDLIBS += $(shell pkg-config --libs $(PKGS)) -lqjs -pthread
31+LDLIBS += $(shell pkg-config --libs $(PKGS)) -pthread
3232
3333 .PHONY: all deps catalog run clean
3434 all: $(BIN)
@@ -58,7 +58,6 @@ deps:
5858 printf 'MISSING %s\n' "$$p"; \
5959 fi; \
6060 done
61- @if [ -f /usr/include/quickjs.h ]; then echo 'ok quickjs'; else echo 'MISSING quickjs'; fi
6261
6362 run: all
6463 ./$(BIN)
src/agent.c+8−30
@@ -161,46 +161,24 @@ static void on_tool_output(const char *chunk, void *user) {
161161 }
162162
163163 static cage_tool_result run_tool(cage_agent *a, turn_state *st, const cage_block *b) {
164- cage_tool_result r = {0};
165- if (!a->runtime) {
166- r.text = xstrdup("codemode: no runtime configured");
167- r.is_error = true;
168- return r;
169- }
170- if (!b->tool_name || strcmp(b->tool_name, cage_codemode_tool().name) != 0) {
171- char msg[256];
172- snprintf(msg, sizeof msg, "codemode: unknown tool \"%s\"", b->tool_name ? b->tool_name : "");
173- r.text = xstrdup(msg);
174- r.is_error = true;
175- return r;
176- }
177-
164+ const char *name = b->tool_name ? b->tool_name : "";
178165 const char *args = b->arguments ? b->arguments : "{}";
179- yyjson_doc *doc = yyjson_read(args, strlen(args), 0);
180- const char *code = NULL;
181- if (doc) {
182- yyjson_val *c = yyjson_obj_get(yyjson_doc_get_root(doc), "code");
183- if (yyjson_is_str(c)) code = yyjson_get_str(c);
184- }
185- if (!code) {
186- yyjson_doc_free(doc);
187- r.text = xstrdup("codemode: missing \"code\" argument");
188- r.is_error = true;
189- return r;
190- }
191166
192- // The run may write anywhere under the working directory, so a diff of the
167+ // Only the tools that can write get a tree diff around them.
168+ if (strcmp(name, "edit") != 0 && strcmp(name, "bash") != 0)
169+ return cage_tool_run(name, args, a->model.supports_images, on_tool_output, st, a->cancel);
170+
171+ // The tool may write anywhere under the working directory, so a diff of the
193172 // tree around it is the only way to report what changed.
194173 struct timespec start;
195174 clock_gettime(CLOCK_REALTIME, &start);
196175 struct cage_snapshot *before = cage_snapshot_capture(NULL);
197- r = cage_runtime_run(a->runtime, code, on_tool_output, st, a->cancel);
176+ cage_tool_result r =
177+ cage_tool_run(name, args, a->model.supports_images, on_tool_output, st, a->cancel);
198178 struct cage_snapshot *after = cage_snapshot_capture(&start);
199179 r.diffs = cage_snapshot_diff(before, after, &r.diffs_len);
200180 cage_snapshot_free(before);
201181 cage_snapshot_free(after);
202-
203- yyjson_doc_free(doc);
204182 return r;
205183 }
206184
src/agent.h+0−4
@@ -9,7 +9,6 @@
99 #include "message.h"
1010 #include "provider.h"
1111 #include "session.h"
12-#include "tool.h"
1312
1413 typedef struct {
1514 // Model and request shape.
@@ -18,9 +17,6 @@ typedef struct {
1817 const cage_tool *tools;
1918 size_t tools_len;
2019
21- // Tool execution. Required once the model asks for a tool.
22- cage_runtime *runtime;
23-
2420 // Persistence. NULL disables session logging.
2521 cage_session *session;
2622
src/codemode.c+0−355
@@ -1,355 +0,0 @@
1-// The codemode runtime: an embedded QuickJS that runs a JavaScript program.
2-
3-#include "tool.h"
4-
5-#include <quickjs.h>
6-#include <stdint.h>
7-#include <stdio.h>
8-#include <stdlib.h>
9-#include <string.h>
10-
11-struct host {
12- char *name;
13- cage_host_fn fn;
14- void *user;
15-};
16-
17-struct cage_runtime {
18- JSRuntime *rt;
19- JSContext *ctx;
20- struct host *hosts;
21- size_t hosts_len;
22- cage_tool_output_fn out;
23- void *out_user;
24- 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;
28-};
29-
30-// ---- small helpers --------------------------------------------------------
31-
32-static void *xmalloc(size_t n) {
33- void *p = malloc(n);
34- if (!p) abort();
35- return p;
36-}
37-
38-static void *xcalloc(size_t n, size_t size) {
39- void *p = calloc(n, size);
40- if (!p) abort();
41- return p;
42-}
43-
44-static char *xstrdup(const char *s) {
45- size_t n = strlen(s) + 1;
46- char *p = xmalloc(n);
47- memcpy(p, s, n);
48- return p;
49-}
50-
51-typedef struct {
52- char *data;
53- size_t len;
54- size_t cap;
55-} buf;
56-
57-static void buf_add(buf *b, const char *p, size_t n) {
58- if (b->len + n + 1 > b->cap) {
59- size_t cap = b->cap ? b->cap : 64;
60- while (cap < b->len + n + 1) cap *= 2;
61- b->data = realloc(b->data, cap);
62- if (!b->data) abort();
63- b->cap = cap;
64- }
65- memcpy(b->data + b->len, p, n);
66- b->len += n;
67- b->data[b->len] = '\0';
68-}
69-
70-// Returns JSON.stringify for objects and the raw text for strings.
71-static char *json_or_text(JSContext *ctx, JSValueConst v) {
72- if (JS_IsString(v)) {
73- const char *s = JS_ToCString(ctx, v);
74- char *r = xstrdup(s ? s : "");
75- JS_FreeCString(ctx, s);
76- return r;
77- }
78- JSValue j = JS_JSONStringify(ctx, v, JS_UNDEFINED, JS_UNDEFINED);
79- if (JS_IsException(j) || JS_IsUndefined(j)) {
80- JS_FreeValue(ctx, j);
81- return xstrdup("");
82- }
83- const char *s = JS_ToCString(ctx, j);
84- char *r = xstrdup(s ? s : "");
85- JS_FreeCString(ctx, s);
86- JS_FreeValue(ctx, j);
87- return r;
88-}
89-
90-// Combines an error's name, message, and stack trace.
91-static char *error_text(JSContext *ctx, JSValueConst v) {
92- if (JS_IsError(v)) {
93- JSValue name = JS_GetPropertyStr(ctx, v, "name");
94- JSValue msg = JS_GetPropertyStr(ctx, v, "message");
95- JSValue stack = JS_GetPropertyStr(ctx, v, "stack");
96- const char *ns = JS_IsString(name) ? JS_ToCString(ctx, name) : NULL;
97- const char *ms = JS_IsString(msg) ? JS_ToCString(ctx, msg) : NULL;
98- const char *ss = JS_IsString(stack) ? JS_ToCString(ctx, stack) : NULL;
99-
100- buf b = {0};
101- if (ss && ns && strncmp(ss, ns, strlen(ns)) == 0) {
102- buf_add(&b, ss, strlen(ss)); // the stack already carries the header
103- } else {
104- if (ns) buf_add(&b, ns, strlen(ns));
105- if (ms) {
106- if (b.len) buf_add(&b, ": ", 2);
107- buf_add(&b, ms, strlen(ms));
108- }
109- if (ss) {
110- if (b.len) buf_add(&b, "\n", 1);
111- buf_add(&b, ss, strlen(ss));
112- }
113- }
114- if (ns) JS_FreeCString(ctx, ns);
115- if (ms) JS_FreeCString(ctx, ms);
116- if (ss) JS_FreeCString(ctx, ss);
117- JS_FreeValue(ctx, name);
118- JS_FreeValue(ctx, msg);
119- JS_FreeValue(ctx, stack);
120- if (b.data) return b.data;
121- }
122- const char *s = JS_ToCString(ctx, v);
123- if (s) {
124- char *r = xstrdup(s);
125- JS_FreeCString(ctx, s);
126- return r;
127- }
128- return xstrdup("codemode: error");
129-}
130-
131-// ---- interpreter hooks ----------------------------------------------------
132-
133-static int on_interrupt(JSRuntime *rt, void *opaque) {
134- (void)rt;
135- cage_runtime *r = opaque;
136- return (r->cancel && *r->cancel) ? 1 : 0;
137-}
138-
139-static JSValue js_log(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) {
140- (void)this_val;
141- cage_runtime *r = JS_GetContextOpaque(ctx);
142- buf b = {0};
143- for (int i = 0; i < argc; i++) {
144- if (i > 0) buf_add(&b, " ", 1);
145- char *s = json_or_text(ctx, argv[i]);
146- buf_add(&b, s, strlen(s));
147- free(s);
148- }
149- buf_add(&b, "\n", 1);
150- if (r->out) r->out(b.data, r->out_user);
151- free(b.data);
152- return JS_UNDEFINED;
153-}
154-
155-static JSValue js_host(JSContext *ctx, JSValueConst this_val, int argc,
156- JSValueConst *argv, int magic, JSValueConst *func_data) {
157- (void)this_val;
158- (void)func_data;
159- cage_runtime *r = JS_GetContextOpaque(ctx);
160- size_t index = (size_t)magic;
161- if (index >= r->hosts_len) return JS_UNDEFINED;
162- struct host *h = &r->hosts[index];
163-
164- JSValue arr = JS_NewArray(ctx);
165- for (int i = 0; i < argc; i++)
166- JS_SetPropertyUint32(ctx, arr, (uint32_t)i, JS_DupValue(ctx, argv[i]));
167- JSValue jargs = JS_JSONStringify(ctx, arr, JS_UNDEFINED, JS_UNDEFINED);
168- JS_FreeValue(ctx, arr);
169- if (JS_IsException(jargs)) {
170- JS_FreeValue(ctx, jargs);
171- return JS_EXCEPTION;
172- }
173- const char *cargs = JS_ToCString(ctx, jargs);
174- JS_FreeValue(ctx, jargs);
175-
176- cage_host_result result = h->fn(cargs ? cargs : "[]", h->user);
177- JS_FreeCString(ctx, cargs);
178-
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);
189- return parsed;
190-}
191-
192-cage_runtime *cage_runtime_new(bool supports_images) {
193- cage_runtime *r = xcalloc(1, sizeof *r);
194- r->rt = JS_NewRuntime();
195- r->ctx = JS_NewContext(r->rt);
196- r->supports_images = supports_images;
197- JS_SetContextOpaque(r->ctx, r);
198- JS_SetInterruptHandler(r->rt, on_interrupt, r);
199-
200- JSValue global = JS_GetGlobalObject(r->ctx);
201- JSValue console = JS_NewObject(r->ctx);
202- JS_SetPropertyStr(r->ctx, console, "log", JS_NewCFunction(r->ctx, js_log, "log", 1));
203- JS_SetPropertyStr(r->ctx, console, "error", JS_NewCFunction(r->ctx, js_log, "error", 1));
204- JS_SetPropertyStr(r->ctx, global, "console", console);
205- JS_FreeValue(r->ctx, global);
206- return r;
207-}
208-
209-void cage_runtime_register(cage_runtime *r, const char *name, cage_host_fn fn, void *user) {
210- size_t index = r->hosts_len;
211- r->hosts = realloc(r->hosts, (index + 1) * sizeof *r->hosts);
212- if (!r->hosts) abort();
213- r->hosts[index] = (struct host){.name = xstrdup(name), .fn = fn, .user = user};
214- r->hosts_len = index + 1;
215-
216- JSValue f = JS_NewCFunctionData(r->ctx, js_host, 1, (int)index, 0, NULL);
217- JSValue global = JS_GetGlobalObject(r->ctx);
218- JS_SetPropertyStr(r->ctx, global, name, f);
219- JS_FreeValue(r->ctx, global);
220-}
221-
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-void cage_runtime_set_supports_images(cage_runtime *r, bool supports_images) {
240- r->supports_images = supports_images;
241-}
242-
243-bool cage_runtime_cancelled(const cage_runtime *r) {
244- return r->cancel && *r->cancel;
245-}
246-
247-void cage_runtime_free(cage_runtime *r) {
248- if (!r) return;
249- for (size_t i = 0; i < r->hosts_len; i++) free(r->hosts[i].name);
250- free(r->hosts);
251- for (size_t i = 0; i < r->images_len; i++) {
252- free(r->images[i].media_type);
253- free(r->images[i].data);
254- }
255- free(r->images);
256- JS_FreeContext(r->ctx);
257- JS_FreeRuntime(r->rt);
258- free(r);
259-}
260-
261-cage_tool_result cage_runtime_run(cage_runtime *r, const char *script,
262- cage_tool_output_fn out, void *out_user,
263- const volatile bool *cancel) {
264- cage_tool_result res = {0};
265- // QuickJS records the stack top at runtime creation and checks overflow
266- // against it. The TUI runs turns on a worker thread, so refresh it here.
267- JS_UpdateStackTop(r->rt);
268- r->out = out;
269- r->out_user = out_user;
270- r->cancel = cancel;
271- r->images = NULL;
272- r->images_len = 0;
273-
274- const char *pre = "(async () => {\n";
275- const char *post = "\n})()";
276- size_t n = strlen(pre) + strlen(script) + strlen(post);
277- char *src = xmalloc(n + 1);
278- memcpy(src, pre, strlen(pre));
279- memcpy(src + strlen(pre), script, strlen(script));
280- memcpy(src + strlen(pre) + strlen(script), post, strlen(post) + 1);
281-
282- JSValue fn = JS_Eval(r->ctx, src, n, "<codemode>", JS_EVAL_TYPE_GLOBAL);
283- free(src);
284-
285- if (cancel && *cancel) {
286- if (JS_IsException(fn)) JS_FreeValue(r->ctx, JS_GetException(r->ctx));
287- else JS_FreeValue(r->ctx, fn);
288- res.text = xstrdup("codemode: aborted");
289- res.is_error = true;
290- goto done;
291- }
292- if (JS_IsException(fn)) {
293- JSValue e = JS_GetException(r->ctx);
294- res.text = error_text(r->ctx, e);
295- res.is_error = true;
296- JS_FreeValue(r->ctx, e);
297- goto done;
298- }
299-
300- JSContext *jc;
301- while (JS_ExecutePendingJob(r->rt, &jc) > 0) {}
302-
303- if (cancel && *cancel) {
304- JS_FreeValue(r->ctx, fn);
305- res.text = xstrdup("codemode: aborted");
306- res.is_error = true;
307- goto done;
308- }
309-
310- switch (JS_PromiseState(r->ctx, fn)) {
311- case JS_PROMISE_FULFILLED: {
312- JSValue v = JS_PromiseResult(r->ctx, fn);
313- res.text = json_or_text(r->ctx, v);
314- JS_FreeValue(r->ctx, v);
315- break;
316- }
317- case JS_PROMISE_REJECTED: {
318- JSValue v = JS_PromiseResult(r->ctx, fn);
319- res.text = error_text(r->ctx, v);
320- res.is_error = true;
321- JS_FreeValue(r->ctx, v);
322- break;
323- }
324- default:
325- res.text = xstrdup("codemode: script did not settle");
326- res.is_error = true;
327- break;
328- }
329- JS_FreeValue(r->ctx, fn);
330-
331-done:
332- res.images = r->images;
333- res.images_len = r->images_len;
334- r->images = NULL;
335- r->images_len = 0;
336- return res;
337-}
338-
339-cage_tool cage_codemode_tool(void) {
340- cage_tool t = {
341- .name = "codemode",
342- .description =
343- "Run a JavaScript program. The program may use await. The globals "
344- "are: read(path) returns a file's text; edit(path, oldText, newText) "
345- "replaces the single occurrence of oldText in a file (empty oldText "
346- "creates it); bash(command) runs a shell command and resolves to "
347- "{ output, exitCode }. Write progress with console.log and return the "
348- "value to report back as the result.",
349- .parameters =
350- "{\"type\":\"object\","
351- "\"properties\":{\"code\":{\"type\":\"string\",\"description\":\"JavaScript to run\"}},"
352- "\"required\":[\"code\"],\"additionalProperties\":false}",
353- };
354- return t;
355-}
src/diff.h+1−1
@@ -1,4 +1,4 @@
1-// cage working-tree diffs: what a codemode run changed on disk.
1+// cage working-tree diffs: what a tool run changed on disk.
22 //
33 // The changes are display-only. A snapshot records the working tree; diffing
44 // the snapshots around a run yields the changed files, each a unified patch or
src/host.h+0−16
@@ -1,16 +0,0 @@
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+4−11
@@ -13,7 +13,6 @@
1313 #include "agent.h"
1414 #include "config.h"
1515 #include "headless.h"
16-#include "host.h"
1716 #include "resolve.h"
1817 #include "resources.h"
1918 #include "tool.h"
@@ -111,8 +110,8 @@ int main(int argc, char **argv) {
111110 return 1;
112111 }
113112
114- cage_runtime *runtime = cage_runtime_new(model.supports_images);
115- cage_hosts_register(runtime);
113+ size_t tools_len;
114+ const cage_tool *tools = cage_tools(model.supports_images, &tools_len);
116115
117116 if (!print_mode) {
118117 // The TUI owns the terminal and its own signal handlers.
@@ -120,11 +119,9 @@ int main(int argc, char **argv) {
120119 .cfg = cfg,
121120 .model = model,
122121 .resources = resources,
123- .runtime = runtime,
124122 .cwd = cwd,
125123 };
126124 int code = cage_tui_run(&tc);
127- cage_runtime_free(runtime);
128125 cage_resources_free(resources);
129126 cage_config_free(cfg);
130127 free(err);
@@ -139,8 +136,6 @@ int main(int argc, char **argv) {
139136 return 1;
140137 }
141138
142- cage_tool tool = cage_codemode_tool();
143-
144139 signal(SIGINT, on_signal);
145140 signal(SIGTERM, on_signal);
146141
@@ -150,10 +145,9 @@ int main(int argc, char **argv) {
150145 cage_agent a = {0};
151146 a.model = model;
152147 a.system_prompt = resources->system_prompt;
153- a.tools = &tool;
154- a.tools_len = 1;
148+ a.tools = tools;
149+ a.tools_len = tools_len;
155150
156- a.runtime = runtime;
157151 a.session = session;
158152 a.on_event = cage_headless_event;
159153 a.user = &head;
@@ -165,7 +159,6 @@ int main(int argc, char **argv) {
165159
166160 cage_agent_free(&a);
167161 cage_headless_free(&head);
168- cage_runtime_free(runtime);
169162 cage_session_close(session);
170163 cage_resources_free(resources);
171164 cage_config_free(cfg);
src/tool.c+132−94
@@ -1,6 +1,6 @@
1-// The read, edit, and bash capabilities, exposed as codemode globals.
1+// The read, edit, and bash tools.
22
3-#include "host.h"
3+#include "tool.h"
44
55 #include <errno.h>
66 #include <fcntl.h>
@@ -63,34 +63,21 @@ static void buf_addz(buf *b, const char *s) {
6363 buf_add(b, s, strlen(s));
6464 }
6565
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];
66+static void set_error(cage_tool_result *res, const char *fmt, ...) {
67+ char detail[1024];
7268 va_list ap;
7369 va_start(ap, fmt);
7470 vsnprintf(detail, sizeof detail, fmt, ap);
7571 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;
72+ res->text = xstrdup(detail);
73+ res->is_error = true;
8674 }
8775
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) {
76+// The named member of `args` when it is a string, else NULL.
77+static const char *arg_str(yyjson_doc *doc, const char *key) {
9078 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);
79+ yyjson_val *v = yyjson_obj_get(yyjson_doc_get_root(doc), key);
80+ return yyjson_is_str(v) ? yyjson_get_str(v) : NULL;
9481 }
9582
9683 // ---- UTF-8 ----------------------------------------------------------------
@@ -253,56 +240,56 @@ static const char *image_mime(const char *path) {
253240
254241 // ---- read -----------------------------------------------------------------
255242
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)) {
243+static void tool_read(const char *args, bool supports_images, cage_tool_result *res) {
244+ yyjson_doc *doc = yyjson_read(args, strlen(args), 0);
245+ const char *path = arg_str(doc, "path");
246+ if (!path) {
247+ set_error(res, "read failed: path must be a string");
261248 yyjson_doc_free(doc);
262- return err("read: path must be a string");
249+ return;
263250 }
264- const char *path = yyjson_get_str(a);
265251
266252 buf data = {0};
267253 if (slurp(path, &data) != 0) {
268- cage_host_result r = err("read failed: %s: %s", path, strerror(errno));
254+ set_error(res, "read failed: %s: %s", path, strerror(errno));
269255 free(data.data);
270256 yyjson_doc_free(doc);
271- return r;
257+ return;
272258 }
273259
274260 const char *mime = image_mime(path);
275261 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);
262+ if (!supports_images) {
263+ set_error(res, "read failed: %s is an image and the current model does not accept image input", path);
278264 free(data.data);
279265 yyjson_doc_free(doc);
280- return r;
266+ return;
281267 }
282268 char *b64 = base64_encode((const unsigned char *)data.data, data.len);
283269 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);
270+ set_error(res, "read failed: %s encodes to %zu bytes, over the %u byte image limit",
271+ path, strlen(b64), MAX_IMAGE_B64);
286272 free(b64);
287273 free(data.data);
288274 yyjson_doc_free(doc);
289- return r;
275+ return;
290276 }
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);
277+ res->text = xmalloc(strlen(path) + strlen(mime) + 64);
278+ sprintf(res->text, "read %s (%s, %zu bytes)", path, mime, data.len);
279+ res->images = xmalloc(sizeof *res->images);
280+ res->images[0] = (cage_image){.media_type = xstrdup(mime), .data = b64};
281+ res->images_len = 1;
295282 free(data.data);
296283 yyjson_doc_free(doc);
297- return ok_json(json_string(msg));
284+ return;
298285 }
299286
300287 size_t sniff = data.len < 8000 ? data.len : 8000;
301288 if (sniff > 0 && memchr(data.data, 0, sniff)) {
302- cage_host_result r = err("read failed: %s is binary; use bash (file, xxd)", path);
289+ set_error(res, "read failed: %s is binary; use bash (file, xxd)", path);
303290 free(data.data);
304291 yyjson_doc_free(doc);
305- return r;
292+ return;
306293 }
307294
308295 size_t take = data.len > MAX_TEXT ? MAX_TEXT : data.len;
@@ -318,18 +305,21 @@ static cage_host_result host_read(const char *args_json, void *user) {
318305 }
319306 free(data.data);
320307 yyjson_doc_free(doc);
321- return ok_json(json_string(clean));
308+ res->text = clean;
322309 }
323310
324311 // ---- edit -----------------------------------------------------------------
325312
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);
313+static void tool_edit(const char *args, cage_tool_result *res) {
314+ yyjson_doc *doc = yyjson_read(args, strlen(args), 0);
315+ yyjson_val *root = doc ? yyjson_doc_get_root(doc) : NULL;
316+ yyjson_val *pa = root ? yyjson_obj_get(root, "path") : NULL;
317+ yyjson_val *oa = root ? yyjson_obj_get(root, "oldText") : NULL;
318+ yyjson_val *na = root ? yyjson_obj_get(root, "newText") : NULL;
330319 if (!yyjson_is_str(pa) || !yyjson_is_str(oa) || !yyjson_is_str(na)) {
320+ set_error(res, "edit failed: path, oldText and newText must be strings");
331321 yyjson_doc_free(doc);
332- return err("edit: path, oldText and newText must be strings");
322+ return;
333323 }
334324 const char *path = yyjson_get_str(pa);
335325 const char *old = yyjson_get_str(oa);
@@ -339,42 +329,42 @@ static cage_host_result host_edit(const char *args_json, void *user) {
339329
340330 if (old_len == 0) {
341331 if (access(path, F_OK) == 0) {
342- cage_host_result r = err("edit failed: %s already exists", path);
332+ set_error(res, "edit failed: %s already exists", path);
343333 yyjson_doc_free(doc);
344- return r;
334+ return;
345335 }
346336 if (spill(path, nw, new_len) != 0) {
347- cage_host_result r = err("edit failed: %s: %s", path, strerror(errno));
337+ set_error(res, "edit failed: %s: %s", path, strerror(errno));
348338 yyjson_doc_free(doc);
349- return r;
339+ return;
350340 }
351- char msg[1024];
352- snprintf(msg, sizeof msg, "created %s", path);
341+ res->text = xmalloc(strlen(path) + 16);
342+ sprintf(res->text, "created %s", path);
353343 yyjson_doc_free(doc);
354- return ok_json(json_string(msg));
344+ return;
355345 }
356346
357347 buf data = {0};
358348 if (slurp(path, &data) != 0) {
359- cage_host_result r = err("edit failed: %s: %s", path, strerror(errno));
349+ set_error(res, "edit failed: %s: %s", path, strerror(errno));
360350 free(data.data);
361351 yyjson_doc_free(doc);
362- return r;
352+ return;
363353 }
364354
365355 size_t at;
366356 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);
357+ set_error(res, "edit failed: oldText not found in %s", path);
368358 free(data.data);
369359 yyjson_doc_free(doc);
370- return r;
360+ return;
371361 }
372362 size_t second;
373363 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);
364+ set_error(res, "edit failed: oldText matches more than once in %s", path);
375365 free(data.data);
376366 yyjson_doc_free(doc);
377- return r;
367+ return;
378368 }
379369
380370 buf out = {0};
@@ -382,19 +372,18 @@ static cage_host_result host_edit(const char *args_json, void *user) {
382372 buf_add(&out, nw, new_len);
383373 buf_add(&out, data.data + at + old_len, data.len - at - old_len);
384374 if (spill(path, out.data, out.len) != 0) {
385- cage_host_result r = err("edit failed: %s: %s", path, strerror(errno));
375+ set_error(res, "edit failed: %s: %s", path, strerror(errno));
386376 free(out.data);
387377 free(data.data);
388378 yyjson_doc_free(doc);
389- return r;
379+ return;
390380 }
391381
392- char msg[1024];
393- snprintf(msg, sizeof msg, "edited %s", path);
382+ res->text = xmalloc(strlen(path) + 16);
383+ sprintf(res->text, "edited %s", path);
394384 free(out.data);
395385 free(data.data);
396386 yyjson_doc_free(doc);
397- return ok_json(json_string(msg));
398387 }
399388
400389 // ---- bash -----------------------------------------------------------------
@@ -408,29 +397,29 @@ static void keep_tail(buf *t, bool *truncated) {
408397 *truncated = true;
409398 }
410399
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)) {
400+static void tool_bash(const char *args, cage_tool_output_fn out, void *user,
401+ const volatile bool *cancel, cage_tool_result *res) {
402+ yyjson_doc *doc = yyjson_read(args, strlen(args), 0);
403+ const char *command = arg_str(doc, "command");
404+ if (!command) {
405+ set_error(res, "bash: command must be a string");
416406 yyjson_doc_free(doc);
417- return err("bash: command must be a string");
407+ return;
418408 }
419- const char *command = yyjson_get_str(a);
420409
421410 int pipefd[2];
422411 if (pipe(pipefd) != 0) {
423- cage_host_result r = err("bash: %s", strerror(errno));
412+ set_error(res, "bash: %s", strerror(errno));
424413 yyjson_doc_free(doc);
425- return r;
414+ return;
426415 }
427416 pid_t pid = fork();
428417 if (pid < 0) {
429418 close(pipefd[0]);
430419 close(pipefd[1]);
431- cage_host_result r = err("bash: fork: %s", strerror(errno));
420+ set_error(res, "bash: fork: %s", strerror(errno));
432421 yyjson_doc_free(doc);
433- return r;
422+ return;
434423 }
435424 if (pid == 0) {
436425 setpgid(0, 0);
@@ -454,7 +443,7 @@ static cage_host_result host_bash(const char *args_json, void *user) {
454443
455444 char chunk[8192];
456445 for (;;) {
457- if (cage_runtime_cancelled(rt)) {
446+ if (cancel && *cancel) {
458447 cancelled = true;
459448 break;
460449 }
@@ -472,7 +461,7 @@ static cage_host_result host_bash(const char *args_json, void *user) {
472461 }
473462 if (n == 0) break;
474463 chunk[n] = '\0';
475- cage_runtime_output(rt, chunk);
464+ if (out) out(chunk, user);
476465 if (head.len < MAX_HEAD) {
477466 size_t take = MAX_HEAD - head.len;
478467 if ((size_t)n < take) take = (size_t)n;
@@ -519,23 +508,72 @@ static cage_host_result host_bash(const char *args_json, void *user) {
519508 buf_add(&body, tail.data ? tail.data : "", tail.len);
520509
521510 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);
511+ buf text = {0};
512+ buf_addz(&text, clean);
513+ if (text.len > 0 && text.data[text.len - 1] != '\n') buf_addz(&text, "\n");
514+ char code_line[32];
515+ snprintf(code_line, sizeof code_line, "exit code: %d", code);
516+ buf_addz(&text, code_line);
517+ res->text = text.data;
518+ res->is_error = code != 0;
529519 free(clean);
530520 free(body.data);
531521 free(head.data);
532522 free(tail.data);
533523 yyjson_doc_free(doc);
534- return ok_json(json);
535524 }
536525
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);
526+// ---- the toolset ----------------------------------------------------------
527+
528+#define READ_DESCRIPTION \
529+ "Read a file. Returns its text. Prefer bash for search, ranges, or binary files."
530+#define READ_IMAGE_DESCRIPTION \
531+ "Read a file. Returns its text, or the image itself when the file is a png, jpg, or webp. " \
532+ "Prefer bash for search, ranges, or binary files."
533+#define EDIT_DESCRIPTION \
534+ "Edit a file by exact text replacement. oldText must occur exactly once. " \
535+ "With empty oldText, create a new file (fails if it exists)."
536+#define BASH_DESCRIPTION "Run a bash command in the current working directory."
537+
538+#define READ_PARAMS \
539+ "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"File path\"}}," \
540+ "\"required\":[\"path\"],\"additionalProperties\":false}"
541+#define EDIT_PARAMS \
542+ "{\"type\":\"object\",\"properties\":{" \
543+ "\"path\":{\"type\":\"string\",\"description\":\"File path\"}," \
544+ "\"oldText\":{\"type\":\"string\",\"description\":\"Exact text to replace; empty to create a file\"}," \
545+ "\"newText\":{\"type\":\"string\",\"description\":\"Replacement text\"}}," \
546+ "\"required\":[\"path\",\"oldText\",\"newText\"],\"additionalProperties\":false}"
547+#define BASH_PARAMS \
548+ "{\"type\":\"object\",\"properties\":{\"command\":{\"type\":\"string\",\"description\":\"Command to run\"}}," \
549+ "\"required\":[\"command\"],\"additionalProperties\":false}"
550+
551+const cage_tool *cage_tools(bool supports_images, size_t *len) {
552+ static const cage_tool plain[] = {
553+ {"read", READ_DESCRIPTION, READ_PARAMS},
554+ {"edit", EDIT_DESCRIPTION, EDIT_PARAMS},
555+ {"bash", BASH_DESCRIPTION, BASH_PARAMS},
556+ };
557+ static const cage_tool images[] = {
558+ {"read", READ_IMAGE_DESCRIPTION, READ_PARAMS},
559+ {"edit", EDIT_DESCRIPTION, EDIT_PARAMS},
560+ {"bash", BASH_DESCRIPTION, BASH_PARAMS},
561+ };
562+ *len = 3;
563+ return supports_images ? images : plain;
564+}
565+
566+cage_tool_result cage_tool_run(const char *name, const char *args, bool supports_images,
567+ cage_tool_output_fn out, void *user, const volatile bool *cancel) {
568+ cage_tool_result res = {0};
569+ if (name && strcmp(name, "read") == 0) {
570+ tool_read(args, supports_images, &res);
571+ } else if (name && strcmp(name, "edit") == 0) {
572+ tool_edit(args, &res);
573+ } else if (name && strcmp(name, "bash") == 0) {
574+ tool_bash(args, out, user, cancel, &res);
575+ } else {
576+ set_error(&res, "unknown tool: %s", name ? name : "");
577+ }
578+ return res;
541579 }
src/tool.h+15−43
@@ -1,9 +1,8 @@
1-// cage tools: the single codemode tool and the JS runtime that executes it.
1+// cage tools: the capabilities the model may call.
22 //
3-// Instead of one tool per capability, the model writes a JavaScript program.
4-// Capabilities are exposed to the script as global functions registered by the
5-// caller (this is the seam where MCP servers will plug in). Sandboxing is not a
6-// feature yet; the embedded runtime is what makes it possible later.
3+// Three plain functions: `read` returns a file's text (or an image), `edit`
4+// replaces text in a file, and `bash` runs a shell command. Each result carries
5+// text, an error flag, optional images, and display-only file diffs.
76
87 #ifndef CAGE_TOOL_H
98 #define CAGE_TOOL_H
@@ -13,7 +12,7 @@
1312
1413 #include "provider.h"
1514
16-// One image a host function attached to the current run.
15+// One image a tool attached to its result.
1716 typedef struct {
1817 char *media_type; // e.g. "image/png"
1918 char *data; // base64 payload
@@ -37,45 +36,18 @@ typedef struct {
3736 size_t diffs_len;
3837 } cage_tool_result;
3938
40-typedef struct cage_runtime cage_runtime;
41-
39+// A tool's streamed output (bash's stdout/stderr), forwarded to the projection.
4240 typedef void (*cage_tool_output_fn)(const char *chunk, void *user);
4341
44-// A host function's outcome: a JSON value string, or an error to throw. Both
45-// fields are owned by the runtime; `error` wins when set.
46-typedef struct {
47- char *json; // JSON value text, or NULL for null
48- char *error; // when set, a JS Error with this message is thrown
49-} cage_host_result;
50-
51-// A host function callable from the script. `args_json` is a JSON array of the
52-// call arguments; the returned strings are owned by the runtime.
53-typedef cage_host_result (*cage_host_fn)(const char *args_json, void *user);
54-
55-// The single tool the model calls.
56-cage_tool cage_codemode_tool(void);
57-
58-// `supports_images` is the model's image-input capability, used to gate `read`.
59-cage_runtime *cage_runtime_new(bool supports_images);
60-void cage_runtime_free(cage_runtime *rt);
61-
62-// Exposes `fn` as a global function named `name` in the runtime.
63-void cage_runtime_register(cage_runtime *rt, const char *name, cage_host_fn fn, void *user);
64-
65-// Host-side accessors used by the capability implementations. `output` forwards
66-// a chunk to the run's output callback; `add_image` attaches an image to the
67-// run's result.
68-void cage_runtime_output(cage_runtime *rt, const char *chunk);
69-void cage_runtime_add_image(cage_runtime *rt, const char *media_type, const char *base64);
70-bool cage_runtime_supports_images(const cage_runtime *rt);
71-void cage_runtime_set_supports_images(cage_runtime *rt, bool supports_images);
72-bool cage_runtime_cancelled(const cage_runtime *rt);
42+// The tools the model may call. `*len` receives the count. `supports_images`
43+// gates whether read's description mentions image input. The array is static
44+// and must not be freed.
45+const cage_tool *cage_tools(bool supports_images, size_t *len);
7346
74-// Runs `script` as an async program. Output chunks go to `out`; the program's
75-// return value becomes the result text. `cancel` is polled by the interpreter
76-// and may be NULL.
77-cage_tool_result cage_runtime_run(cage_runtime *rt, const char *script,
78- cage_tool_output_fn out, void *out_user,
79- const volatile bool *cancel);
47+// Executes `name` with `args`, a JSON object string. An unknown tool name yields
48+// an error result. `out` forwards streamed output and may be NULL. `cancel` is
49+// polled by bash and may be NULL.
50+cage_tool_result cage_tool_run(const char *name, const char *args, bool supports_images,
51+ cage_tool_output_fn out, void *user, const volatile bool *cancel);
8052
Cut short: this commit's diff is over 1000 lines.
src/tui/commands.c+78−75
Cut short: this commit's diff is over 1000 lines.
src/tui/commands.h+22−0
Cut short: this commit's diff is over 1000 lines.
src/tui/tui.c+179−17
Cut short: this commit's diff is over 1000 lines.
src/tui/tui.h+0−1
Cut short: this commit's diff is over 1000 lines.