xonecas.io
7814
Ta

tiny-c-agent / files

tiny-c-agent / src / agent.c

10.2 KB
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#include <time.h>
10
11#include <yyjson.h>
12
13#include "diff.h"
14#include "util.h"
15
16// Per-turn state passed to the provider and tool callbacks.
17typedef struct {
18    tiny_agent *a;
19    bool streaming;
20} turn_state;
21
22// ---- event helpers --------------------------------------------------------
23
24static void emit(tiny_agent *a, const tiny_event *e) {
25    if (a->on_event) a->on_event(e, a->user);
26}
27
28static void emit_phase(tiny_agent *a, tiny_phase phase, const char *detail) {
29    tiny_event e = {.type = TINY_EVENT_PHASE};
30    e.u.phase.phase = phase;
31    e.u.phase.detail = detail;
32    emit(a, &e);
33}
34
35static void emit_error(tiny_agent *a, const char *msg) {
36    tiny_event e = {.type = TINY_EVENT_ERROR};
37    e.u.error.message = msg ? msg : "";
38    emit(a, &e);
39}
40
41static void emit_simple(tiny_agent *a, tiny_event_type type) {
42    tiny_event e = {.type = type};
43    emit(a, &e);
44}
45
46// ---- transcript and session -----------------------------------------------
47
48// Appends the message to the transcript and, when configured, to the session.
49// On a persistence failure the turn must stop, so this reports the error.
50static int push_message(tiny_agent *a, tiny_message *m, char **err) {
51    a->messages = realloc(a->messages, (a->messages_len + 1) * sizeof *a->messages);
52    if (!a->messages) abort();
53    a->messages[a->messages_len++] = *m;
54    if (!a->session) return 0;
55
56    yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
57    yyjson_mut_val *record = yyjson_mut_obj(doc);
58    yyjson_mut_doc_set_root(doc, record);
59    yyjson_mut_obj_add_strcpy(doc, record, "type", "message");
60    yyjson_mut_obj_add_val(doc, record, "message", tiny_message_to_val(doc, m));
61    char *serr = NULL;
62    int rc = tiny_session_append(a->session, record, &serr);
63    yyjson_mut_doc_free(doc);
64    if (rc != 0) {
65        *err = serr ? serr : xstrdup("session append failed");
66        return -1;
67    }
68    return 0;
69}
70
71static int push_user(tiny_agent *a, const char *text, char **err) {
72    tiny_message m = tiny_message_user(text);
73    return push_message(a, &m, err);
74}
75
76// ---- interruption ---------------------------------------------------------
77
78// Checks the cancel flag and, at a step boundary, a pause request. On pause it
79// blocks for steering. Returns false when the turn was cancelled.
80static bool pause_step(tiny_agent *a, char **steer) {
81    *steer = NULL;
82    if (a->cancel && *a->cancel) return false;
83    if (!a->is_pause_requested || !a->is_pause_requested(a->user)) return true;
84    if (a->clear_pause) a->clear_pause(a->user);
85    emit_phase(a, TINY_PHASE_PAUSING, NULL);
86    char *s = a->request_steering ? a->request_steering(a->user) : NULL;
87    emit_phase(a, TINY_PHASE_IDLE, NULL);
88    if (a->cancel && *a->cancel) {
89        free(s);
90        return false;
91    }
92    *steer = s;
93    return true;
94}
95
96// ---- provider and tool callbacks ------------------------------------------
97
98static void on_stream(const tiny_stream_event *ev, void *user) {
99    turn_state *st = user;
100    if (!st->streaming) {
101        st->streaming = true;
102        emit_phase(st->a, TINY_PHASE_STREAMING, NULL);
103    }
104    tiny_event e = {0};
105    switch (ev->type) {
106    case TINY_STREAM_TEXT_DELTA:
107        e.type = TINY_EVENT_TEXT;
108        e.u.text.delta = ev->delta;
109        break;
110    case TINY_STREAM_REASONING_DELTA:
111        e.type = TINY_EVENT_REASONING;
112        e.u.reasoning.delta = ev->delta;
113        break;
114    case TINY_STREAM_TOOL_CALL_START:
115        e.type = TINY_EVENT_TOOL_CALL_START;
116        e.u.tool_call_start.name = ev->tool_name;
117        break;
118    case TINY_STREAM_TOOL_CALL:
119        e.type = TINY_EVENT_TOOL_CALL;
120        e.u.tool_call.name = ev->tool_name;
121        e.u.tool_call.arguments = ev->tool_arguments;
122        break;
123    default:
124        return;
125    }
126    emit(st->a, &e);
127}
128
129static void on_tool_output(const char *chunk, void *user) {
130    turn_state *st = user;
131    tiny_event e = {.type = TINY_EVENT_TOOL_OUTPUT};
132    e.u.tool_output.chunk = chunk;
133    emit(st->a, &e);
134}
135
136static tiny_tool_result run_tool(tiny_agent *a, turn_state *st, const tiny_block *b) {
137    const char *name = b->tool_name ? b->tool_name : "";
138    const char *args = b->arguments ? b->arguments : "{}";
139
140    // Only bash can write anywhere under the working directory, so a diff of
141    // the tree around it is the only way to report what changed. `edit` reports
142    // its own diff from the content it already read.
143    if (strcmp(name, "bash") != 0)
144        return tiny_tool_run(name, args, a->model.supports_images, on_tool_output, st, a->cancel);
145
146    // The tool may write anywhere under the working directory, so a diff of the
147    // tree around it is the only way to report what changed.
148    struct timespec start;
149    clock_gettime(CLOCK_REALTIME, &start);
150    struct tiny_snapshot *before = tiny_snapshot_capture(NULL);
151    tiny_tool_result r =
152        tiny_tool_run(name, args, a->model.supports_images, on_tool_output, st, a->cancel);
153    struct tiny_snapshot *after = tiny_snapshot_capture(&start);
154    r.diffs = tiny_snapshot_diff(before, after, &r.diffs_len);
155    tiny_snapshot_free(before);
156    tiny_snapshot_free(after);
157    return r;
158}
159
160// ---- the loop -------------------------------------------------------------
161
162void tiny_agent_turn(tiny_agent *a, const char *input) {
163    if (!a->model.model || !a->model.base_url) {
164        emit_simple(a, TINY_EVENT_NO_MODEL);
165        return;
166    }
167
168    char *perr = NULL;
169    if (input && input[0] && push_user(a, input, &perr) != 0) {
170        emit_error(a, perr);
171        free(perr);
172        return;
173    }
174
175    for (;;) {
176        char *steer = NULL;
177        if (!pause_step(a, &steer)) {
178            emit_simple(a, TINY_EVENT_CANCELLED);
179            return;
180        }
181        if (steer && steer[0] && push_user(a, steer, &perr) != 0) {
182            free(steer);
183            emit_error(a, perr);
184            free(perr);
185            return;
186        }
187        free(steer);
188
189        emit_phase(a, TINY_PHASE_PREPARING, NULL);
190
191        turn_state st = {.a = a, .streaming = false};
192        tiny_context ctx = {
193            .system_prompt = a->system_prompt,
194            .tools = a->tools,
195            .tools_len = a->tools_len,
196            .messages = a->messages,
197            .messages_len = a->messages_len,
198        };
199        tiny_stream_opts opts = {
200            .effort = a->model.effort,
201            .session_id = a->session ? tiny_session_id(a->session) : NULL,
202        };
203
204        emit_phase(a, TINY_PHASE_WAITING_MODEL, NULL);
205        tiny_message asst = {0};
206        char *serr = NULL;
207        if (tiny_provider_stream(&a->model, &ctx, &opts, on_stream, &st, a->cancel, &asst, &serr) != 0) {
208            emit_error(a, serr ? serr : "provider error");
209            free(serr);
210            tiny_message_free(&asst);
211            return;
212        }
213
214        if (push_message(a, &asst, &perr) != 0) {
215            emit_error(a, perr);
216            free(perr);
217            return;
218        }
219        char *json = tiny_message_to_json(&asst);
220        tiny_event me = {.type = TINY_EVENT_MESSAGE};
221        me.u.message.json = json ? json : "{}";
222        emit(a, &me);
223        free(json);
224
225        if (asst.stop_reason && strcmp(asst.stop_reason, "aborted") == 0) {
226            emit_simple(a, TINY_EVENT_CANCELLED);
227            return;
228        }
229        if (asst.stop_reason && strcmp(asst.stop_reason, "error") == 0) {
230            emit_error(a, asst.error_message ? asst.error_message : "provider error");
231            return;
232        }
233
234        size_t calls = 0;
235        for (size_t i = 0; i < asst.blocks_len; i++)
236            if (asst.blocks[i].type == TINY_BLOCK_TOOL_CALL) calls++;
237        if (calls == 0) {
238            emit_simple(a, TINY_EVENT_COMPLETE);
239            return;
240        }
241
242        // Steering is held until every result of this assistant turn has landed.
243        tiny_buf held = {0};
244        bool cancelled = false;
245        for (size_t i = 0; i < asst.blocks_len && !cancelled; i++) {
246            tiny_block *b = &asst.blocks[i];
247            if (b->type != TINY_BLOCK_TOOL_CALL) continue;
248
249            char *s2 = NULL;
250            if (!pause_step(a, &s2)) {
251                free(s2);
252                cancelled = true;
253                break;
254            }
255            if (s2 && s2[0]) {
256                if (held.len) buf_add(&held, "\n", 1);
257                buf_add(&held, s2, strlen(s2));
258            }
259            free(s2);
260
261            emit_phase(a, TINY_PHASE_RUNNING_TOOL, b->tool_name);
262            tiny_tool_result tr = run_tool(a, &st, b);
263            tiny_message tm = tiny_message_tool(b->tool_call_id, tr.text, tr.is_error);
264            free(tr.text);
265            for (size_t k = 0; k < tr.images_len; k++) {
266                tiny_block *ib = tiny_message_add_block(&tm, TINY_BLOCK_IMAGE);
267                ib->media_type = xstrdup(tr.images[k].media_type);
268                ib->data = xstrdup(tr.images[k].data);
269                free(tr.images[k].media_type);
270                free(tr.images[k].data);
271            }
272            free(tr.images);
273
274            if (push_message(a, &tm, &perr) != 0) {
275                free(held.data);
276                tiny_file_diffs_free(tr.diffs, tr.diffs_len);
277                emit_error(a, perr);
278                free(perr);
279                return;
280            }
281            tiny_event re = {.type = TINY_EVENT_TOOL_RESULT};
282            re.u.tool_result.name = b->tool_name;
283            re.u.tool_result.text = tm.blocks_len ? tm.blocks[0].text : "";
284            re.u.tool_result.is_error = tm.is_error;
285            re.u.tool_result.diffs = tr.diffs;
286            re.u.tool_result.diffs_len = tr.diffs_len;
287            emit(a, &re);
288            tiny_file_diffs_free(tr.diffs, tr.diffs_len);
289        }
290
291        if (cancelled) {
292            free(held.data);
293            emit_simple(a, TINY_EVENT_CANCELLED);
294            return;
295        }
296        if (held.len && push_user(a, held.data, &perr) != 0) {
297            free(held.data);
298            emit_error(a, perr);
299            free(perr);
300            return;
301        }
302        free(held.data);
303    }
304}
305
306void tiny_agent_free(tiny_agent *a) {
307    for (size_t i = 0; i < a->messages_len; i++) tiny_message_free(&a->messages[i]);
308    free(a->messages);
309    a->messages = NULL;
310    a->messages_len = 0;
311}