xonecas.io
7814
Ta

tiny-c-agent / commit 49e00a8

feat: initial agent gen

xonecas2026-10-02 49e00a86dd2ccc1f61e3c8f764d8fea05baf4b94

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

.gitignore+3−0
@@ -0,0 +1,3 @@
1+build/
2+*.o
3+*.d
AGENTS.md+45−0
@@ -0,0 +1,45 @@
1+# Project file for agents
2+
3+## c-agent (`cage` for short)
4+
5+A fast, minimal and config first agent for your terminal.
6+
7+## References
8+
9+- `../mini-coder` - A very similar implementation in typescript. An example do not blindly copy.
10+
11+## Some guardrails
12+
13+- **Write original code.** Other coding agents are behavioral references only.
14+- **No loop limits.** No max turns, tool calls, token budgets, or agent-imposed
15+ timeouts. The user's ability to interrupt is the limit.
16+- **Config-first.** Every user-facing behavior that can vary comes from config
17+ with a sane default.
18+- **Minimal context.** The model sees the configured system prompt plus
19+ explicitly opted-in resource files — never reminders, hidden blocks, or
20+ harness meta-text.
21+- **The agent never imports the TUI.** Headless and TUI are two projections of
22+ the same agent events; the TUI owns no agent or provider semantics.
23+- **Respect linux/unix coventions**. Both for storing configs and state, as well as making sure the head
24+ less mode is scriptable.
25+
26+## Invariants
27+
28+- Sessions are append-only JSONL, one message per line, fsynced on
29+ write. Never rewrite or delete committed lines. A persistence failure stops
30+ the turn.
31+- The loop has no compaction, no retries, and no meta-messages between steps.
32+ Provider errors surface as-is, never masked or summarized.
33+- Single codemode-style LLM tool, exectutes the script in a JS environment.
34+- Interruption: ESC politely pauses at the next step boundary; Ctrl+C cancels the
35+ turn (abort the request, kill the tool's process group, persist the aborted
36+ message); Ctrl+C (or CTRL+D) exits on an empty draft. Completed side effects are never
37+ undone.
38+- Diagnostics are local only. No telemetry, no hidden stalls.
39+
40+## Working agreement
41+
42+- Trace the real data flow before designing; apply guards at the narrowest
43+ boundary.
44+- Keep the diff small. Do not opportunistically refactor or harden adjacent code.
45+- Do not add tests unless explicitly asked; verify manually.
Makefile+63−0
@@ -0,0 +1,63 @@
1+# cage - config-first agent for the terminal.
2+#
3+# make build
4+# make deps report build dependencies
5+# make run build and run
6+# make clean remove build/
7+
8+CC ?= cc
9+STD ?= gnu11
10+OPT ?= -O2 -g
11+WARN := -Wall -Wextra -Wshadow -Wstrict-prototypes -Wmissing-prototypes -Wpointer-arith
12+
13+BUILD := build
14+BIN := $(BUILD)/cage
15+
16+PKGS := libuv libcurl ncursesw yyjson tree-sitter \
17+ tree-sitter-javascript tree-sitter-bash
18+
19+TSJSON := third_party/tree-sitter-json
20+
21+SRCS := $(shell find src -name '*.c' | sort)
22+OBJS := $(patsubst src/%.c,$(BUILD)/obj/%.o,$(SRCS))
23+TSJSON_OBJ := $(BUILD)/obj/$(TSJSON)/src/parser.o
24+DEPS := $(OBJS:.o=.d) $(TSJSON_OBJ:.o=.d)
25+
26+BASE := -std=$(STD) $(OPT)
27+
28+CPPFLAGS += -D_GNU_SOURCE -Isrc -I$(TSJSON)/src -MMD -MP
29+CFLAGS += $(BASE) $(WARN) $(shell pkg-config --cflags $(PKGS))
30+LDLIBS += $(shell pkg-config --libs $(PKGS)) -lqjs
31+
32+.PHONY: all deps run clean
33+all: $(BIN)
34+
35+$(BIN): $(OBJS) $(TSJSON_OBJ)
36+ $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(LDLIBS)
37+
38+$(BUILD)/obj/%.o: src/%.c
39+ @mkdir -p $(dir $@)
40+ $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<
41+
42+# Vendored grammars are generated code and are built without the project warnings.
43+$(TSJSON_OBJ): $(TSJSON)/src/parser.c
44+ @mkdir -p $(dir $@)
45+ $(CC) $(CPPFLAGS) $(BASE) -c -o $@ $<
46+
47+deps:
48+ @for p in $(PKGS); do \
49+ if pkg-config --exists $$p; then \
50+ printf 'ok %s %s\n' "$$p" "$$(pkg-config --modversion $$p)"; \
51+ else \
52+ printf 'MISSING %s\n' "$$p"; \
53+ fi; \
54+ done
55+ @if [ -f /usr/include/quickjs.h ]; then echo 'ok quickjs'; else echo 'MISSING quickjs'; fi
56+
57+run: all
58+ ./$(BIN)
59+
60+clean:
61+ rm -rf $(BUILD)
62+
63+-include $(DEPS)
initial.md+104−0
@@ -0,0 +1,104 @@
1+# c-agent (`cage` for short)
2+
3+A fast, minimal and config-first agent for your terminal.
4+
5+## Config
6+
7+The config lives at the user's configured config folder (usually ~/.config).
8+
9+A custom config can be provided via `--config/-c [path to file]` as a CLI argument.
10+If a custom config was specified, and there is a global config, they are merged with the local
11+config overriding the global.
12+
13+Config schema:
14+
15+```jsonc
16+{
17+ "theme": "tokyo-night", // string | undefined, the color palette to use.
18+ "provider": "", // string | undefined
19+ "model": "", // string | undefined
20+ "effort": "", // string| undefined; off, minimal, low, medium, high, xhigh, max, depends on model, needs to be clamped on model selection. Default is we don't send one, let the provider decide.
21+ "systemPrompt": "", // path | undefined, the path to a markdown or text file to use as system prompt
22+ "discoverAgentFiles": true, // boolean | true, if we should discover and append AGENTS.md to the prompt
23+ "skillsDirs": [], // [path, ...] | [], list of directories to search for SKILL.md files.
24+ "sessionsDir": "", // path | undefined, defaults to .local/state or the appropriate Unix convention,
25+ "customProviders": [], // see right below.
26+}
27+```
28+
29+Custom providers example:
30+
31+```json
32+{
33+ "customProviders": [
34+ {
35+ "id": "ollama",
36+ "name": "Ollama",
37+ "baseUrl": "http://localhost:11434/v1",
38+ "api": "openai-completions",
39+ "models": ["qwen3-coder:30b", "gpt-oss:20b"]
40+ },
41+ // ...
42+ ]
43+}
44+```
45+
46+### Extra details
47+
48+**Theme**: It can be a choice of `tokyo-night` or `auto`, defaults to tokyo. Auto is a theme that uses the host terminal theme. Plenty of CLIs do this, it shouldn't be a complicated thing. It should be just as detailed and accurate as tokyo-night.
49+**provider**: The provider id you want to use from one of the supported providers. Initially this is opencode-go and opencode-zen via an OPENCODE_API_KEY from the env. Or the id of one of your configured customProviders.
50+**model**: the model id for the specific model you want to use from the configured provider.
51+**effort**: pre-clamp, user configured value for effort. (models vary a lot on this, so the effective effort post clamp is shown in the TUI). This configures the desire of the user, not the effective value.
52+**custom providers**: api is openai-completions, openai-responses, anthropic-messages, or google-generative-ai. Then point provider and model at it.
53+
54+## Agent core
55+
56+Stays very similar in concept to mini-coder's with the exception of the tools.
57+
58+The agent core needs to be interruptible, a polite request to pause at the next boundary for steering.
59+It also needs to be cancelable, and this needs to be responsive.
60+
61+### Tools
62+
63+A single, codemode style tool. https://blog.cloudflare.com/code-mode/ similar in concept to this. Instead of providing several tools, we provide a single code runtime, where we can expose configurable mcps, along with a runtime and standard library. QuickJS comes to mind as a nice embeddable option. Sandboxing is not a feature for now, but an embedded runtime would help us go this way in the future.
64+We currently don't plan to support MCP, but this is the foundation we need to do so eventually.
65+We render the call, and an elided body just like mini-coder does it, and we show the diff of the changes just like mini-coder does with bash calls.
66+
67+- Capabilities: bash exec, read/write to file system, read images. (same as mini-coder but in code mode).
68+
69+## Providers
70+
71+We aim to support Opencode Zen, Opencode Go and local models via customProviders.
72+
73+Instead of supporting all specific providers, we implement 4 modules, one for each major API format. This allows us to support the whole opencode catalog, without a specific implementation per model.
74+Model catalog: we should generate this from a reliable source so we have details about models, like context size, supported effort levels, etc.
75+
76+We can look at the open-source pi-ai for reference.
77+
78+## Headless mode
79+
80+Prints the ongoing statuses to stderr, and tool activity (no tool bodies), and prints the final assistant response to stdout.
81+Can be used in script scenarios, pipes and input redirect, etc.
82+Accepts a `-p/--print` CLI argument as well.
83+
84+## TUI
85+
86+We are going to use the mini-coder UX/Appearance as a specification for how we render reasoning, tool bodies, user and assistant responses, errors, etc.
87+
88+At startup as part of the banner, we should show the loaded agents file if any. Same for skills. So the user knows whats up right away.
89+
90+Same commands as mini-coder, but with the addition of `/new` to start a new session.
91+
92+### Themes
93+
94+Our themes appear both in the chrome of the app, as well as syntax highlighting and diff rendering (see how
95+mini-coder does it). We use tree-sitter and their respective grammars. Then we follow `nvim`'s usage of it.
96+We intend to have this small set of themes:
97+
98+- Tokyo Night (night variant).
99+- Auto (tries to use the host terminal's theme).
100+
101+## Tech
102+
103+Modern C11
104+tree-sitter and its grammars (nvim is a good reference I think, open source and also uses tree sitter).
src/agent.c+332−0
@@ -0,0 +1,332 @@
1+// The agent loop: one turn runs the provider, executes tool calls, and appends
2+// every message to the transcript and the session.
3+
4+#include "agent.h"
5+
6+#include <stdio.h>
7+#include <stdlib.h>
8+#include <string.h>
9+
10+#include <yyjson.h>
11+
12+// Per-turn state passed to the provider and tool callbacks.
13+typedef struct {
14+ cage_agent *a;
15+ bool streaming;
16+} turn_state;
17+
18+static void *xmalloc(size_t n) {
19+ void *p = malloc(n);
20+ if (!p) abort();
21+ return p;
22+}
23+
24+static char *xstrdup(const char *s) {
25+ size_t n = strlen(s) + 1;
26+ char *p = xmalloc(n);
27+ memcpy(p, s, n);
28+ return p;
29+}
30+
31+typedef struct {
32+ char *data;
33+ size_t len;
34+ size_t cap;
35+} buf;
36+
37+static void buf_add(buf *b, const char *p, size_t n) {
38+ if (b->len + n + 1 > b->cap) {
39+ size_t cap = b->cap ? b->cap : 64;
40+ while (cap < b->len + n + 1) cap *= 2;
41+ b->data = realloc(b->data, cap);
42+ if (!b->data) abort();
43+ b->cap = cap;
44+ }
45+ memcpy(b->data + b->len, p, n);
46+ b->len += n;
47+ b->data[b->len] = '\0';
48+}
49+
50+// ---- event helpers --------------------------------------------------------
51+
52+static void emit(cage_agent *a, const cage_event *e) {
53+ if (a->on_event) a->on_event(e, a->user);
54+}
55+
56+static void emit_phase(cage_agent *a, cage_phase phase, const char *detail) {
57+ cage_event e = {.type = CAGE_EVENT_PHASE};
58+ e.u.phase.phase = phase;
59+ e.u.phase.detail = detail;
60+ emit(a, &e);
61+}
62+
63+static void emit_error(cage_agent *a, const char *msg) {
64+ cage_event e = {.type = CAGE_EVENT_ERROR};
65+ e.u.error.message = msg ? msg : "";
66+ emit(a, &e);
67+}
68+
69+static void emit_simple(cage_agent *a, cage_event_type type) {
70+ cage_event e = {.type = type};
71+ emit(a, &e);
72+}
73+
74+// ---- transcript and session -----------------------------------------------
75+
76+// Appends the message to the transcript and, when configured, to the session.
77+// On a persistence failure the turn must stop, so this reports the error.
78+static int push_message(cage_agent *a, cage_message *m, char **err) {
79+ a->messages = realloc(a->messages, (a->messages_len + 1) * sizeof *a->messages);
80+ if (!a->messages) abort();
81+ a->messages[a->messages_len++] = *m;
82+ if (!a->session) return 0;
83+
84+ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
85+ yyjson_mut_val *record = yyjson_mut_obj(doc);
86+ yyjson_mut_doc_set_root(doc, record);
87+ yyjson_mut_obj_add_strcpy(doc, record, "type", "message");
88+ yyjson_mut_obj_add_val(doc, record, "message", cage_message_to_val(doc, m));
89+ char *serr = NULL;
90+ int rc = cage_session_append(a->session, record, &serr);
91+ yyjson_mut_doc_free(doc);
92+ if (rc != 0) {
93+ *err = serr ? serr : xstrdup("session append failed");
94+ return -1;
95+ }
96+ return 0;
97+}
98+
99+static int push_user(cage_agent *a, const char *text, char **err) {
100+ cage_message m = cage_message_user(text);
101+ return push_message(a, &m, err);
102+}
103+
104+// ---- interruption ---------------------------------------------------------
105+
106+// Checks the cancel flag and, at a step boundary, a pause request. On pause it
107+// blocks for steering. Returns false when the turn was cancelled.
108+static bool pause_step(cage_agent *a, char **steer) {
109+ *steer = NULL;
110+ if (a->cancel && *a->cancel) return false;
111+ if (!a->is_pause_requested || !a->is_pause_requested(a->user)) return true;
112+ if (a->clear_pause) a->clear_pause(a->user);
113+ emit_phase(a, CAGE_PHASE_PAUSING, NULL);
114+ char *s = a->request_steering ? a->request_steering(a->user) : NULL;
115+ emit_phase(a, CAGE_PHASE_IDLE, NULL);
116+ if (a->cancel && *a->cancel) {
117+ free(s);
118+ return false;
119+ }
120+ *steer = s;
121+ return true;
122+}
123+
124+// ---- provider and tool callbacks ------------------------------------------
125+
126+static void on_stream(const cage_stream_event *ev, void *user) {
127+ turn_state *st = user;
128+ if (!st->streaming) {
129+ st->streaming = true;
130+ emit_phase(st->a, CAGE_PHASE_STREAMING, NULL);
131+ }
132+ cage_event e = {0};
133+ switch (ev->type) {
134+ case CAGE_STREAM_TEXT_DELTA:
135+ e.type = CAGE_EVENT_TEXT;
136+ e.u.text.delta = ev->delta;
137+ break;
138+ case CAGE_STREAM_REASONING_DELTA:
139+ e.type = CAGE_EVENT_REASONING;
140+ e.u.reasoning.delta = ev->delta;
141+ break;
142+ case CAGE_STREAM_TOOL_CALL:
143+ e.type = CAGE_EVENT_TOOL_CALL;
144+ e.u.tool_call.name = ev->tool_name;
145+ e.u.tool_call.arguments = ev->tool_arguments;
146+ break;
147+ default:
148+ return;
149+ }
150+ emit(st->a, &e);
151+}
152+
153+static void on_tool_output(const char *chunk, void *user) {
154+ turn_state *st = user;
155+ cage_event e = {.type = CAGE_EVENT_TOOL_OUTPUT};
156+ e.u.tool_output.chunk = chunk;
157+ emit(st->a, &e);
158+}
159+
160+static cage_tool_result run_tool(cage_agent *a, turn_state *st, const cage_block *b) {
161+ cage_tool_result r = {0};
162+ if (!a->runtime) {
163+ r.text = xstrdup("codemode: no runtime configured");
164+ r.is_error = true;
165+ return r;
166+ }
167+ if (!b->tool_name || strcmp(b->tool_name, cage_codemode_tool().name) != 0) {
168+ char msg[256];
169+ snprintf(msg, sizeof msg, "codemode: unknown tool \"%s\"", b->tool_name ? b->tool_name : "");
170+ r.text = xstrdup(msg);
171+ r.is_error = true;
172+ return r;
173+ }
174+
175+ const char *args = b->arguments ? b->arguments : "{}";
176+ yyjson_doc *doc = yyjson_read(args, strlen(args), 0);
177+ const char *code = NULL;
178+ if (doc) {
179+ yyjson_val *c = yyjson_obj_get(yyjson_doc_get_root(doc), "code");
180+ if (yyjson_is_str(c)) code = yyjson_get_str(c);
181+ }
182+ if (!code) {
183+ yyjson_doc_free(doc);
184+ r.text = xstrdup("codemode: missing \"code\" argument");
185+ r.is_error = true;
186+ return r;
187+ }
188+ r = cage_runtime_run(a->runtime, code, on_tool_output, st, a->cancel);
189+ yyjson_doc_free(doc);
190+ return r;
191+}
192+
193+// ---- the loop -------------------------------------------------------------
194+
195+void cage_agent_turn(cage_agent *a, const char *input) {
196+ if (!a->model.model || !a->model.base_url) {
197+ emit_simple(a, CAGE_EVENT_NO_MODEL);
198+ return;
199+ }
200+
201+ char *perr = NULL;
202+ if (input && input[0] && push_user(a, input, &perr) != 0) {
203+ emit_error(a, perr);
204+ free(perr);
205+ return;
206+ }
207+
208+ for (;;) {
209+ char *steer = NULL;
210+ if (!pause_step(a, &steer)) {
211+ emit_simple(a, CAGE_EVENT_CANCELLED);
212+ return;
213+ }
214+ if (steer && steer[0] && push_user(a, steer, &perr) != 0) {
215+ free(steer);
216+ emit_error(a, perr);
217+ free(perr);
218+ return;
219+ }
220+ free(steer);
221+
222+ emit_phase(a, CAGE_PHASE_PREPARING, NULL);
223+
224+ turn_state st = {.a = a, .streaming = false};
225+ cage_context ctx = {
226+ .system_prompt = a->system_prompt,
227+ .tools = a->tools,
228+ .tools_len = a->tools_len,
229+ .messages = a->messages,
230+ .messages_len = a->messages_len,
231+ };
232+ cage_stream_opts opts = {
233+ .effort = a->effort,
234+ .session_id = a->session ? cage_session_id(a->session) : NULL,
235+ };
236+
237+ emit_phase(a, CAGE_PHASE_WAITING_MODEL, NULL);
238+ cage_message asst = {0};
239+ char *serr = NULL;
240+ if (cage_provider_stream(&a->model, &ctx, &opts, on_stream, &st, a->cancel, &asst, &serr) != 0) {
241+ emit_error(a, serr ? serr : "provider error");
242+ free(serr);
243+ cage_message_free(&asst);
244+ return;
245+ }
246+
247+ if (push_message(a, &asst, &perr) != 0) {
248+ emit_error(a, perr);
249+ free(perr);
250+ return;
251+ }
252+ char *json = cage_message_to_json(&asst);
253+ cage_event me = {.type = CAGE_EVENT_MESSAGE};
254+ me.u.message.json = json ? json : "{}";
255+ emit(a, &me);
256+ free(json);
257+
258+ if (asst.stop_reason && strcmp(asst.stop_reason, "aborted") == 0) {
259+ emit_simple(a, CAGE_EVENT_CANCELLED);
260+ return;
261+ }
262+ if (asst.stop_reason && strcmp(asst.stop_reason, "error") == 0) {
263+ emit_error(a, asst.error_message ? asst.error_message : "provider error");
264+ return;
265+ }
266+
267+ size_t calls = 0;
268+ for (size_t i = 0; i < asst.blocks_len; i++)
269+ if (asst.blocks[i].type == CAGE_BLOCK_TOOL_CALL) calls++;
270+ if (calls == 0) {
271+ emit_simple(a, CAGE_EVENT_COMPLETE);
272+ return;
273+ }
274+
275+ // Steering is held until every result of this assistant turn has landed.
276+ buf held = {0};
277+ bool cancelled = false;
278+ for (size_t i = 0; i < asst.blocks_len && !cancelled; i++) {
279+ cage_block *b = &asst.blocks[i];
280+ if (b->type != CAGE_BLOCK_TOOL_CALL) continue;
281+
282+ char *s2 = NULL;
283+ if (!pause_step(a, &s2)) {
284+ free(s2);
285+ cancelled = true;
286+ break;
287+ }
288+ if (s2 && s2[0]) {
289+ if (held.len) buf_add(&held, "\n", 1);
290+ buf_add(&held, s2, strlen(s2));
291+ }
292+ free(s2);
293+
294+ emit_phase(a, CAGE_PHASE_RUNNING_TOOL, b->tool_name);
295+ cage_tool_result tr = run_tool(a, &st, b);
296+ cage_message tm = cage_message_tool(b->tool_call_id, tr.text, tr.is_error);
297+ free(tr.text);
298+
299+ if (push_message(a, &tm, &perr) != 0) {
300+ free(held.data);
301+ emit_error(a, perr);
302+ free(perr);
303+ return;
304+ }
305+ cage_event re = {.type = CAGE_EVENT_TOOL_RESULT};
306+ re.u.tool_result.name = b->tool_name;
307+ re.u.tool_result.text = tm.blocks_len ? tm.blocks[0].text : "";
308+ re.u.tool_result.is_error = tm.is_error;
309+ emit(a, &re);
310+ }
311+
312+ if (cancelled) {
313+ free(held.data);
314+ emit_simple(a, CAGE_EVENT_CANCELLED);
315+ return;
316+ }
317+ if (held.len && push_user(a, held.data, &perr) != 0) {
318+ free(held.data);
319+ emit_error(a, perr);
320+ free(perr);
321+ return;
322+ }
323+ free(held.data);
324+ }
325+}
326+
327+void cage_agent_free(cage_agent *a) {
328+ for (size_t i = 0; i < a->messages_len; i++) cage_message_free(&a->messages[i]);
329+ free(a->messages);
330+ a->messages = NULL;
331+ a->messages_len = 0;
332+}
src/agent.h+51−0
@@ -0,0 +1,51 @@
1+// cage agent: the loop that binds provider, session, and tool.
2+
3+#ifndef CAGE_AGENT_H
4+#define CAGE_AGENT_H
5+
6+#include <stdbool.h>
7+
8+#include "event.h"
9+#include "message.h"
10+#include "provider.h"
11+#include "session.h"
12+#include "tool.h"
13+
14+typedef struct {
15+ // Model and request shape.
16+ cage_model model;
17+ const char *system_prompt;
18+ const cage_tool *tools;
19+ size_t tools_len;
20+ const char *effort;
21+
22+ // Tool execution. Required once the model asks for a tool.
23+ cage_runtime *runtime;
24+
25+ // Persistence. NULL disables session logging.
26+ cage_session *session;
27+
28+ // Projection. Both projections receive the same event stream.
29+ cage_event_fn on_event;
30+ void *user;
31+
32+ // Interruption. All optional; NULL means the feature is absent.
33+ bool (*is_pause_requested)(void *user);
34+ void (*clear_pause)(void *user);
35+ char *(*request_steering)(void *user); // returns malloc'd text, or NULL
36+ const volatile bool *cancel;
37+
38+ // Transcript, owned by the agent and kept across turns.
39+ cage_message *messages;
40+ size_t messages_len;
41+} cage_agent;
42+
43+// Appends `input` as a user message, then loops until the model stops without
44+// tool calls. Every outcome is reported as an event: complete, cancelled, or
45+// error. The caller owns `model`, `runtime`, `session`, and the tools.
46+void cage_agent_turn(cage_agent *a, const char *input);
47+
48+// Frees the transcript. Does not free the runtime, session, or model strings.
49+void cage_agent_free(cage_agent *a);
50+
51+#endif
src/api.h+14−0
@@ -0,0 +1,14 @@
1+// Internal contract between the provider dispatcher and each API adapter.
2+
3+#ifndef CAGE_API_H
4+#define CAGE_API_H
5+
6+#include "provider.h"
7+
8+int cage_openai_completions_stream(const cage_model *model, const cage_context *ctx,
9+ const cage_stream_opts *opts,
10+ cage_stream_fn emit, void *user,
11+ const volatile bool *cancel,
12+ cage_message *out, char **err);
13+
14+#endif
src/api/openai_completions.c+534−0
@@ -0,0 +1,534 @@
1+// OpenAI-compatible chat completions: the wire format behind Opencode Zen/Go
2+// and every customProvider with api "openai-completions".
3+
4+#include "api.h"
5+
6+#include <curl/curl.h>
7+#include <stdarg.h>
8+#include <stdio.h>
9+#include <stdlib.h>
10+#include <string.h>
11+
12+#include <yyjson.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+// ---- growable byte buffer -------------------------------------------------
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 void *p, size_t n) {
46+ if (b->len + n + 1 > b->cap) {
47+ size_t cap = b->cap ? b->cap : 128;
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+
58+static void buf_free(buf *b) {
59+ free(b->data);
60+ b->data = NULL;
61+ b->len = b->cap = 0;
62+}
63+
64+// ---- request building -----------------------------------------------------
65+
66+// Concatenates a message's text blocks into one string.
67+static char *join_text(const cage_message *m) {
68+ buf b = {0};
69+ for (size_t i = 0; i < m->blocks_len; i++)
70+ if (m->blocks[i].type == CAGE_BLOCK_TEXT && m->blocks[i].text)
71+ buf_add(&b, m->blocks[i].text, strlen(m->blocks[i].text));
72+ buf_add(&b, "", 0);
73+ return b.data;
74+}
75+
76+static void add_message(yyjson_mut_doc *doc, yyjson_mut_val *arr, const cage_message *m) {
77+ yyjson_mut_val *o = yyjson_mut_obj(doc);
78+ yyjson_mut_arr_add_val(arr, o);
79+
80+ if (m->role == CAGE_ROLE_TOOL) {
81+ yyjson_mut_obj_add_strcpy(doc, o, "role", "tool");
82+ yyjson_mut_obj_add_strcpy(doc, o, "tool_call_id", m->tool_call_id ? m->tool_call_id : "");
83+ char *t = join_text(m);
84+ yyjson_mut_obj_add_strcpy(doc, o, "content", t);
85+ free(t);
86+ return;
87+ }
88+ if (m->role == CAGE_ROLE_USER) {
89+ yyjson_mut_obj_add_strcpy(doc, o, "role", "user");
90+ char *t = join_text(m);
91+ yyjson_mut_obj_add_strcpy(doc, o, "content", t);
92+ free(t);
93+ return;
94+ }
95+
96+ yyjson_mut_obj_add_strcpy(doc, o, "role", "assistant");
97+ char *t = join_text(m);
98+ yyjson_mut_obj_add_strcpy(doc, o, "content", t);
99+ free(t);
100+
101+ bool has_calls = false;
102+ yyjson_mut_val *calls = yyjson_mut_arr(doc);
103+ for (size_t i = 0; i < m->blocks_len; i++) {
104+ const cage_block *b = &m->blocks[i];
105+ if (b->type != CAGE_BLOCK_TOOL_CALL) continue;
106+ has_calls = true;
107+ yyjson_mut_val *tc = yyjson_mut_obj(doc);
108+ yyjson_mut_arr_add_val(calls, tc);
109+ yyjson_mut_obj_add_strcpy(doc, tc, "id", b->tool_call_id ? b->tool_call_id : "");
110+ yyjson_mut_obj_add_strcpy(doc, tc, "type", "function");
111+ yyjson_mut_val *fn = yyjson_mut_obj(doc);
112+ yyjson_mut_obj_add_val(doc, tc, "function", fn);
113+ yyjson_mut_obj_add_strcpy(doc, fn, "name", b->tool_name ? b->tool_name : "");
114+ yyjson_mut_obj_add_strcpy(doc, fn, "arguments", b->arguments ? b->arguments : "{}");
115+ }
116+ if (has_calls) yyjson_mut_obj_add_val(doc, o, "tool_calls", calls);
117+}
118+
119+static void add_tools(yyjson_mut_doc *doc, yyjson_mut_val *root, const cage_context *ctx) {
120+ if (ctx->tools_len == 0) return;
121+ yyjson_mut_val *tools = yyjson_mut_arr(doc);
122+ yyjson_mut_obj_add_val(doc, root, "tools", tools);
123+ for (size_t i = 0; i < ctx->tools_len; i++) {
124+ const cage_tool *t = &ctx->tools[i];
125+ yyjson_mut_val *tool = yyjson_mut_obj(doc);
126+ yyjson_mut_arr_add_val(tools, tool);
127+ yyjson_mut_obj_add_strcpy(doc, tool, "type", "function");
128+ yyjson_mut_val *fn = yyjson_mut_obj(doc);
129+ yyjson_mut_obj_add_val(doc, tool, "function", fn);
130+ yyjson_mut_obj_add_strcpy(doc, fn, "name", t->name);
131+ yyjson_mut_obj_add_strcpy(doc, fn, "description", t->description ? t->description : "");
132+ const char *params = t->parameters ? t->parameters : "{}";
133+ yyjson_doc *pdoc = yyjson_read(params, strlen(params), 0);
134+ if (pdoc) {
135+ yyjson_mut_val *copy = yyjson_val_mut_copy(doc, yyjson_doc_get_root(pdoc));
136+ yyjson_mut_obj_add_val(doc, fn, "parameters", copy);
137+ yyjson_doc_free(pdoc);
138+ }
139+ }
140+}
141+
142+static char *build_request(const cage_model *model, const cage_context *ctx,
143+ const cage_stream_opts *opts) {
144+ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
145+ yyjson_mut_val *root = yyjson_mut_obj(doc);
146+ yyjson_mut_doc_set_root(doc, root);
147+
148+ yyjson_mut_obj_add_strcpy(doc, root, "model", model->model ? model->model : "");
149+ yyjson_mut_obj_add_bool(doc, root, "stream", true);
150+ yyjson_mut_val *so = yyjson_mut_obj(doc);
151+ yyjson_mut_obj_add_bool(doc, so, "include_usage", true);
152+ yyjson_mut_obj_add_val(doc, root, "stream_options", so);
153+
154+ if (opts && opts->effort && strcmp(opts->effort, "off") != 0)
155+ yyjson_mut_obj_add_strcpy(doc, root, "reasoning_effort", opts->effort);
156+ if (opts && opts->max_tokens > 0)
157+ yyjson_mut_obj_add_int(doc, root, "max_tokens", opts->max_tokens);
158+
159+ yyjson_mut_val *messages = yyjson_mut_arr(doc);
160+ yyjson_mut_obj_add_val(doc, root, "messages", messages);
161+ if (ctx->system_prompt && ctx->system_prompt[0]) {
162+ yyjson_mut_val *sys = yyjson_mut_obj(doc);
163+ yyjson_mut_arr_add_val(messages, sys);
164+ yyjson_mut_obj_add_strcpy(doc, sys, "role", "system");
165+ yyjson_mut_obj_add_strcpy(doc, sys, "content", ctx->system_prompt);
166+ }
167+ for (size_t i = 0; i < ctx->messages_len; i++)
168+ add_message(doc, messages, &ctx->messages[i]);
169+
170+ add_tools(doc, root, ctx);
171+
172+ size_t len = 0;
173+ char *body = yyjson_mut_write(doc, 0, &len);
174+ yyjson_mut_doc_free(doc);
175+ return body;
176+}
177+
178+// ---- streaming state ------------------------------------------------------
179+
180+typedef struct {
181+ char *id;
182+ char *name;
183+ buf args;
184+} tool_acc;
185+
186+typedef struct {
187+ buf pending; // bytes not yet split into SSE lines
188+ buf raw; // response body, kept only for error messages
189+ buf text;
190+ buf reasoning;
191+ tool_acc *calls;
192+ size_t calls_len;
193+ char *finish_reason;
194+ long tokens_in;
195+ long tokens_out;
196+ long tokens_total;
197+ char *error;
198+ int http_status;
199+ const volatile bool *cancel;
200+ cage_stream_fn emit;
201+ void *user;
202+} sse_state;
203+
204+static void emit_delta(sse_state *st, cage_stream_type type, const char *delta) {
205+ if (!st->emit) return;
206+ cage_stream_event ev = {.type = type, .delta = delta};
207+ st->emit(&ev, st->user);
208+}
209+
210+static void grow_calls(sse_state *st, size_t count) {
211+ if (count <= st->calls_len) return;
212+ st->calls = realloc(st->calls, count * sizeof *st->calls);
213+ if (!st->calls) abort();
214+ memset(&st->calls[st->calls_len], 0, (count - st->calls_len) * sizeof *st->calls);
215+ st->calls_len = count;
216+}
217+
218+static void handle_delta(sse_state *st, yyjson_val *delta) {
219+ yyjson_val *content = yyjson_obj_get(delta, "content");
220+ if (yyjson_is_str(content) && yyjson_get_str(content)[0]) {
221+ const char *s = yyjson_get_str(content);
222+ buf_add(&st->text, s, strlen(s));
223+ emit_delta(st, CAGE_STREAM_TEXT_DELTA, s);
224+ }
225+
226+ static const char *const reasoning_fields[] = {"reasoning_content", "reasoning", "reasoning_text"};
227+ for (size_t i = 0; i < sizeof reasoning_fields / sizeof reasoning_fields[0]; i++) {
228+ yyjson_val *r = yyjson_obj_get(delta, reasoning_fields[i]);
229+ if (!yyjson_is_str(r) || !yyjson_get_str(r)[0]) continue;
230+ const char *s = yyjson_get_str(r);
231+ buf_add(&st->reasoning, s, strlen(s));
232+ emit_delta(st, CAGE_STREAM_REASONING_DELTA, s);
233+ break;
234+ }
235+
236+ yyjson_val *tcs = yyjson_obj_get(delta, "tool_calls");
237+ if (!yyjson_is_arr(tcs)) return;
238+ size_t idx, max;
239+ yyjson_val *tc;
240+ yyjson_arr_foreach(tcs, idx, max, tc) {
241+ yyjson_val *iv = yyjson_obj_get(tc, "index");
242+ size_t index = yyjson_is_int(iv) ? (size_t)yyjson_get_int(iv) : st->calls_len;
243+ grow_calls(st, index + 1);
244+ tool_acc *a = &st->calls[index];
245+ yyjson_val *id = yyjson_obj_get(tc, "id");
246+ if (yyjson_is_str(id)) {
247+ free(a->id);
248+ a->id = xstrdup(yyjson_get_str(id));
249+ }
250+ yyjson_val *fn = yyjson_obj_get(tc, "function");
251+ if (!yyjson_is_obj(fn)) continue;
252+ yyjson_val *name = yyjson_obj_get(fn, "name");
253+ if (yyjson_is_str(name)) {
254+ free(a->name);
255+ a->name = xstrdup(yyjson_get_str(name));
256+ }
257+ yyjson_val *args = yyjson_obj_get(fn, "arguments");
258+ if (yyjson_is_str(args)) {
259+ const char *s = yyjson_get_str(args);
260+ buf_add(&a->args, s, strlen(s));
261+ }
262+ }
263+}
264+
265+static void handle_data(sse_state *st, const char *json, size_t len) {
266+ yyjson_doc *doc = yyjson_read(json, len, 0);
267+ if (!doc) {
268+ if (!st->error) st->error = xstrdup("stream: invalid JSON chunk");
269+ return;
270+ }
271+ yyjson_val *root = yyjson_doc_get_root(doc);
272+
273+ yyjson_val *err = yyjson_obj_get(root, "error");
274+ if (err) {
275+ if (!st->error) {
276+ const char *msg = NULL;
277+ if (yyjson_is_obj(err)) {
278+ yyjson_val *m = yyjson_obj_get(err, "message");
279+ if (yyjson_is_str(m)) msg = yyjson_get_str(m);
280+ } else if (yyjson_is_str(err)) {
281+ msg = yyjson_get_str(err);
282+ }
283+ st->error = xstrdup(msg ? msg : "stream: provider error");
284+ }
285+ yyjson_doc_free(doc);
286+ return;
287+ }
288+
289+ yyjson_val *choices = yyjson_obj_get(root, "choices");
290+ if (yyjson_is_arr(choices) && yyjson_arr_size(choices) > 0) {
291+ yyjson_val *choice = yyjson_arr_get_first(choices);
292+ yyjson_val *delta = yyjson_obj_get(choice, "delta");
293+ if (yyjson_is_obj(delta)) handle_delta(st, delta);
294+ yyjson_val *fr = yyjson_obj_get(choice, "finish_reason");
295+ if (yyjson_is_str(fr)) {
296+ free(st->finish_reason);
297+ st->finish_reason = xstrdup(yyjson_get_str(fr));
298+ }
299+ }
300+
301+ yyjson_val *usage = yyjson_obj_get(root, "usage");
302+ if (yyjson_is_obj(usage)) {
303+ yyjson_val *v;
304+ if (yyjson_is_num(v = yyjson_obj_get(usage, "prompt_tokens"))) st->tokens_in = (long)yyjson_get_num(v);
305+ if (yyjson_is_num(v = yyjson_obj_get(usage, "completion_tokens"))) st->tokens_out = (long)yyjson_get_num(v);
306+ if (yyjson_is_num(v = yyjson_obj_get(usage, "total_tokens"))) st->tokens_total = (long)yyjson_get_num(v);
307+ }
308+ yyjson_doc_free(doc);
309+}
310+
311+static void handle_line(sse_state *st, const char *line, size_t len) {
312+ if (len < 5 || memcmp(line, "data:", 5) != 0) return;
313+ const char *p = line + 5;
314+ const char *end = line + len;
315+ while (p < end && *p == ' ') p++;
316+ if (end - p == 6 && memcmp(p, "[DONE]", 6) == 0) return;
317+ if (end > p) handle_data(st, p, (size_t)(end - p));
318+}
319+
320+static void sse_feed(sse_state *st, const char *data, size_t n) {
321+ buf_add(&st->pending, data, n);
322+ size_t start = 0;
323+ for (size_t i = 0; i < st->pending.len; i++) {
324+ if (st->pending.data[i] != '\n') continue;
325+ size_t end = i;
326+ if (end > start && st->pending.data[end - 1] == '\r') end--;
327+ handle_line(st, st->pending.data + start, end - start);
328+ start = i + 1;
329+ }
330+ if (start > 0) {
331+ memmove(st->pending.data, st->pending.data + start, st->pending.len - start);
332+ st->pending.len -= start;
333+ st->pending.data[st->pending.len] = '\0';
334+ }
335+}
336+
337+static void sse_free(sse_state *st) {
338+ buf_free(&st->pending);
339+ buf_free(&st->raw);
340+ buf_free(&st->text);
341+ buf_free(&st->reasoning);
342+ for (size_t i = 0; i < st->calls_len; i++) {
343+ free(st->calls[i].id);
344+ free(st->calls[i].name);
345+ buf_free(&st->calls[i].args);
346+ }
347+ free(st->calls);
348+ free(st->finish_reason);
349+ free(st->error);
350+}
351+
352+static void finalize(sse_state *st, cage_message *out) {
353+ if (st->reasoning.len > 0) {
354+ cage_block *b = cage_message_add_block(out, CAGE_BLOCK_THINKING);
355+ b->text = xstrdup(st->reasoning.data);
356+ }
357+ if (st->text.len > 0) {
358+ cage_block *b = cage_message_add_block(out, CAGE_BLOCK_TEXT);
359+ b->text = xstrdup(st->text.data);
360+ }
361+ for (size_t i = 0; i < st->calls_len; i++) {
362+ tool_acc *a = &st->calls[i];
363+ if (!a->name && a->args.len == 0) continue;
364+ cage_block *b = cage_message_add_block(out, CAGE_BLOCK_TOOL_CALL);
365+ b->tool_call_id = xstrdup(a->id ? a->id : "");
366+ b->tool_name = xstrdup(a->name ? a->name : "");
367+ b->arguments = xstrdup(a->args.len ? a->args.data : "{}");
368+ if (st->emit) {
369+ cage_stream_event ev = {
370+ .type = CAGE_STREAM_TOOL_CALL,
371+ .tool_call_id = b->tool_call_id,
372+ .tool_name = b->tool_name,
373+ .tool_arguments = b->arguments,
374+ };
375+ st->emit(&ev, st->user);
376+ }
377+ }
378+ out->tokens_in = st->tokens_in;
379+ out->tokens_out = st->tokens_out;
380+ out->tokens_total = st->tokens_total;
Cut short: this commit's diff is over 1000 lines.
src/codemode.c+299−0
Cut short: this commit's diff is over 1000 lines.
src/config.c+375−0
Cut short: this commit's diff is over 1000 lines.
src/config.h+51−0
Cut short: this commit's diff is over 1000 lines.
src/event.h+51−0
Cut short: this commit's diff is over 1000 lines.
src/headless.c+92−0
Cut short: this commit's diff is over 1000 lines.
src/headless.h+36−0
Cut short: this commit's diff is over 1000 lines.
src/main.c+169−0
Cut short: this commit's diff is over 1000 lines.
src/message.c+109−0
Cut short: this commit's diff is over 1000 lines.
src/message.h+59−0
Cut short: this commit's diff is over 1000 lines.
src/provider.c+20−0
Cut short: this commit's diff is over 1000 lines.
src/provider.h+74−0
Cut short: this commit's diff is over 1000 lines.
src/resolve.c+54−0
Cut short: this commit's diff is over 1000 lines.
src/resolve.h+15−0
Cut short: this commit's diff is over 1000 lines.
src/session.c+222−0
Cut short: this commit's diff is over 1000 lines.
src/session.h+26−0
Cut short: this commit's diff is over 1000 lines.
src/tool.h+45−0
Cut short: this commit's diff is over 1000 lines.
third_party/tree-sitter-json/LICENSE+21−0
Cut short: this commit's diff is over 1000 lines.
third_party/tree-sitter-json/README.md+9−0
Cut short: this commit's diff is over 1000 lines.
third_party/tree-sitter-json/src/parser.c+1061−0
Cut short: this commit's diff is over 1000 lines.
third_party/tree-sitter-json/src/tree_sitter/parser.h+266−0
Cut short: this commit's diff is over 1000 lines.