Guides
Embed
Link the runtime through the C ABI, embed a Sofuu brain archive, and call into JavaScript from a host application.
On this page8 sections
libsofuu exposes the runtime through a small C ABI. A host creates a runtime, calls JSON-enveloped methods or evaluates JavaScript, registers host-side tools the agent can call, and frees every buffer the library returns.
Build and link
make libsofuu
# dist/libsofuu.a
# dist/libsofuu.dylib (or .so)
# dist/sofuu_embed.h
make headless-test
make libsofuu builds the static and shared libraries plus the public header. make headless-test compiles and runs asserting C samples against that library.
Minimal lifecycle
#include "sofuu_embed.h"
SofuuRuntime *rt = sofuu_rt_new(NULL); /* NULL = all defaults */
if (!rt) {
return 1;
}
char *out = NULL;
sofuu_rt_call(rt, "memory.open",
"{\"path\":\"./brain.qtsq\",\"dim\":768}", &out);
/* out is a JSON envelope; free it with sofuu_free, never free() */
if (out) sofuu_free(out);
out = NULL;
sofuu_rt_eval(rt, "1 + 1", &out); /* {"ok":true,"result":2} */
if (out) sofuu_free(out);
sofuu_rt_free(rt);
sofuu_rt_new takes an optional JSON config. The useful keys include embedded, config_root, api_keys, brain_path, enable_signals, and the request defaults provider, model, and base_url. Per-call values always win over the defaults. embedded: true changes process.exit into a catchable ExitError instead of terminating the host.
sofuu_rt_eval is the escape hatch: it evaluates JavaScript with full runtime power when the funnel does not expose the call you need. sofuu_rt_call takes a dot-path method such as ai.complete, memory.recall, or agent.run, plus a JSON object or array of arguments.
Host tools
A native capability becomes an agent tool.
static const char *take_photo(const char *args_json, uint64_t call_id,
void *opaque) {
return "{\"path\":\"/var/tmp/frame.jpg\"}"; /* synchronous result */
}
sofuu_rt_register_host_tool(rt, "take_photo", "Takes a photo with the camera",
NULL, take_photo, NULL);
Returning NULL means the host has taken the call and will settle it later with sofuu_rt_host_tool_resolve(rt, call_id, result_json, error). That resolve is safe from any thread; the result is delivered through the runtime's event loop. The wait is bounded by the agent's tool timeout: 30 seconds per tool by default, or toolTimeoutMs per agent. A host that never answers produces a tool-timeout error rather than a hung turn. A JSON string result reaches the model as text; any other JSON value reaches it as JSON text.
Streaming and cancellation
int sofuu_rt_call_stream(SofuuRuntime *rt, const char *method,
const char *args_json,
void (*on_event)(const char *event_json, void *),
void *opaque, uint64_t *out_cancel_id);
The streaming entry handles two shapes: methods that take an onStep option (agent.run) forward each step, and async iterables (ai.stream, ai.streamLocal) are drained as delta events. Either way the stream ends with exactly one terminal {"kind":"done", ...} event, carrying the result or the error, so a host waiting on done cannot hang. *out_cancel_id is written before the stream starts, so a callback can cancel in flight with sofuu_rt_cancel(rt, cancel_id).
Errors, memory, and threads
Every fallible call returns a JSON envelope in the same shape:
{ "ok": false, "error": { "code": "js_exception", "message": "..." } }
| Code | Meaning |
|---|---|
invalid_arg | A required pointer was NULL. |
bad_args | The args_json payload is not valid JSON. |
unknown_method | The method does not exist in this build. Use it for capability detection. |
js_exception | The method threw: provider error, budget, missing key, or dimension mismatch. |
panic | A contained Rust panic. The process survives; the runtime is poisoned. |
internal | The engine could not produce a result. |
C-level vector entries also return typed integers, including SOFUU_ERR_UNKNOWN_SPACE (-7), SOFUU_ERR_MODEL_UNAVAIL (-8), and SOFUU_ERR_PANIC (-10).
Every buffer the library hands out is allocated with malloc and is NUL-terminated when it is a string. Release it with sofuu_free, which is the library's own free, so hosts with a different CRT never cross allocators. Never free() a pointer you did not receive from a sofuu_* call, and never pass a host-owned buffer expecting the library to free it. Streaming callback strings are borrow-only and valid for the duration of the callback.
One runtime is owned by one thread. All calls on it happen on that thread. Multiple runtimes per process are architecturally supported, each on its own thread over one serialized libuv loop, but single-runtime-per-thread is the verified mode; treat concurrent multi-instance I/O as serialized. sofuu_rt_host_tool_resolve is the sanctioned cross-thread path. sofuu_embed_set_log_cb is process-global and should be installed before runtimes exist.
A contained panic returns SOFUU_ERR_PANIC and an error.code of "panic". The runtime that panicked is not guaranteed recoverable; free it with sofuu_rt_free and create a fresh one on the owning thread. The host process itself is not taken down.
Bindings
Swift and Kotlin wrappers sit over the same ABI.
import Sofuu
let sofuu = try Sofuu()
let brain = try Brain.openDefault(sofuu: sofuu)
try brain.remember("user prefers dark mode")
let hits = try brain.recall("theme preference", k: 1)
print(hits.first?.text ?? "")
On Android, the wrapper exposes eval, embedLocal, streaming with a cancel listener, and host-tool registration. Verify package coordinates against the artifacts your release actually published. QuickJS interprets rather than JITs, so the runtime allocates no executable memory, but that is not a blanket store-acceptance guarantee.
Method funnel
Promoted namespaces are ai, memory, mcp, agent, rlm, http, and web. tools.list and tools.describe resolve, but that read-side surface is deferred; chat.* is declined by design for hosts.
Handle-returning methods (memory.open, mcp.connect, http.serve) return a small JSON object; later calls pass {"handle": N, ...}, and the most recent handle is used when handle is omitted. Close a handle when you are done with it.