Reference
API reference The global sofuu object: AI, HTTP, filesystem, web, memory, tools, MCP, and native modules.
Updated Nov 13, 2026 5 min read v0.3.0-beta Copy page
On this page12 sections Every script has a sofuu object in its root scope; no import needed. This page documents the namespaces evidenced in the runtime sources and the embedding funnel. It is a beta surface: methods can change, and a method that exists does not mean its backend is configured.
ai
Method Shape Notes completecomplete(prompt, config?) → Promise<{text, usage, raw}>usage is {promptTokens, completionTokens}. Messages accept an images array.streamstream(prompt, config?) → AsyncIteratorYields chunks as they arrive; each carries .text. embedembed(text, config?)Defaults to the local sem2-64 space at 64 dimensions . Explicit providers may need network access. embedBatchembedBatch(texts[], config?)Local-only batch; one Float32Array per input. embedImageembedImage(bytes)Uint8Array bytes to a 64-dimensional unit vector in the joint text-image space.embedLocalembedLocal(text)Bundled offline embedding, synchronous, no network: 768 dimensions . similaritysimilarity(a, b)Cosine similarity over native SIMD kernels. dot / l2dot(a, b) / l2(a, b)Dot product and L2 distance over the same kernels. estimateTokensestimateTokens(text)Fast count estimate for prompt budgeting.
Two embedding spaces, two dimensions
sofuu.ai.embed() defaults to 64 dimensions; sofuu.ai.embedLocal() returns 768 . A memory file is written in one space and one dimension. Query and stored vectors must agree on both, or recall fails with E_DIM. Pick one pair per .qtsq file and stay in it.
http
Method Shape Notes createServercreateServer(handler) → serverNon-blocking server over OS sockets. The handler receives req and res. listenserver.listen(port, host)Binds and refs the handle; unref() and ref() control loop holding. fetchfetch(url, opts?)Client over statically linked curl, resolving to .text() and .json(). Also global fetch. serveserve({handler, port, host})Funnel form for embedded hosts: handler is the name of a global function defined through the host, not a closure.
fs
Method Shape Notes readFile / writeFile / appendFile(path, data?)Read, overwrite, and append. readdir / mkdir / rm / existsreaddir(path), mkdir(path), rm(path), exists(path)Directory listing, creation, removal, and existence. setRoot / clearRootsetRoot(path) / clearRoot()Confines relative reads to a root. Absolute paths and symlink escapes are refused while a root is set. spawnspawn()Global, not an fs member: launches a child process with an argument list and returns its output.
web
Method Shape Notes searchsearch(text)Keyless web search; returns ranked result snippets. openopen(url)Fetches a page and returns cleaned, reader-friendly text.
Both touch the network. Policy applies to the host; a call is the host's own choice, not the model's.
memory
Method Shape Notes openopen(path, vecDim, options?)Opens a QTSQ container. options.adapter routes to qdrant, pinecone, or pgvector; options.plaintext selects an explicit zero-KDF open. rememberremember(vectorOrText, text?, role?, turn?)Stores vector, timestamp, and text. A plain string is embedded for you. recallrecall(queryVectorOrText, k)Top k records with distance (0 is an exact match) and similarity. count / statscount() / stats()Record total and capacity metrics; stats() returns JSON text. flush / forget / closeflush(), forget(...), close()Durability and lifecycle. Opening a file another writer holds is refused with E_LOCKED. list / exportlist(opts) / export()Paged listing and unencrypted export. rememberWorking / promoteWorking / clearWorkingsee above Session working set, held in RAM until promoted or dropped.
sofuu.storage.open(path) opens a structured store with .messages, .traces, and a .kv facade.
Method Shape Notes executeexecute(name, args)Runs a builtin or host tool in-process behind the policy layer. list / describelist() / describe(name)Inventory and schema, including policy verdicts. mcpResultmcpResult(result, meta)Maps an MCP result into {ok, text, data?, error?, meta}. PACKSPACKS.coding / .web / .memory / .systemToolpacks for coding, web, memory, and system tools.
The coding pack jails filesystem and execution tools to the project directory; SOFUU_NO_SHELL=1 removes the shell tool.
agent
Method Shape Notes definedefine({name, system?, tools, budget?}) → handleValidates the tool list; an unknown name or duplicate agent name throws. runrun(handleOrNameOrDef, task, opts?) → Promise<AgentResult>The execution loop. Requires a configured model provider. list / cancellist() / cancel(id)Enumerate and cancel runs. renderTracerenderTrace(result)Step trace. resolveApproval / pendingApprovalsresolveApproval(id, allow, always) / pendingApprovals()Settles a host approval request.
mcp
Method Shape Notes connectconnect("cmd --flag"), connect({command, args, env, cwd}), or connect({url, transport})stdio by default; http or auto for Streamable HTTP; sse on explicit request; direct for an in-process server. disconnect() closes it.callcall(method, params, {timeoutMs})Per-call deadline; on expiry the client sends notifications/cancelled. listTools / listResourceslistTools() / listResources()Follows nextCursor and returns the full inventory. serveserve({name, version}) → serverServer object with tool, resource, prompt, use, start, and stop. loadConfigloadConfig()Reads ~/.sofuu/mcp.json, overridable with SOFUU_MCP_CONFIG. A corrupt file is reported and left in place. serverTool / serverStart / serverStopfunnel forms Wires a registered host tool by name and drives the lifecycle.
rlm and ml
sofuu.rlm.query(text, q, opts?) runs a recursive long-context reader loop over documents that exceed the model window, and sofuu.rlm.route(...) routes a query. sofuu.ml.info() reports the five on-device context-economy gates; machine-local diagnostics with no stability contract.
Compatibility globals
Binding Behavior setTimeout / setInterval / clearTimeout / clearIntervalNative event-loop timers. sleep(ms)Synchronous halt of the whole event loop. Avoid in a server. console.log / console.time / console.timeEndStandard output and high-resolution timing. process.argv, process.env, process.cwd(), process.exit(code), process.stdout.write(s)Process surface; process.version reports 0.3.0-beta.
Node and Web compatibility
Standard Supported primitives Web standards TextEncoder, TextDecoder, URL, URLSearchParams, atob, btoa, Headers, Request, ResponseWeb platform globals structuredClone, Blob/File/FormData, Event/EventTarget/CustomEvent, MessageChannel/MessagePort, navigator, persistent localStorage backed by .sofuu/localStorage.jsonWeb Crypto crypto.randomUUID() from OS entropy, crypto.getRandomValues(), crypto.subtle.digest("SHA-256")Streams ReadableStream, WritableStream, TransformStream, TextDecoderStream, TextEncoderStream; Response.body is a stable ReadableStreamnode:fsreadFileSync, writeFileSync, existsSync, readdirSync, mkdirSync, unlinkSync, statSync, promisesnode:pathjoin, resolve, normalize, isAbsolute, relative, dirname, basename, extname, parse, format, sepnode:bufferBuffer.from, alloc, concat, isBuffer, byteLength, toString, copy, slicenode:eventsEventEmitter with on, once, off, emit, listeners, listenerCount, setMaxListenersnode:processnextTick, version, platform, arch, versionsAI SDKs openai, @anthropic-ai/sdk, @modelcontextprotocol/sdk, zod
JavaScript runs on QuickJS at ES2023 with no JIT and no native addons. TypeScript is transformed in-process — types erased, enums and constructor parameter properties lowered — so sofuu run app.ts needs no tsc step. Node built-ins are shims for the primitives above, not the whole node: surface.
Where to go next
Server and inference covers createServer and sofuu serve; troubleshooting maps error codes to checks.
PreviousKaze 1.0 reference Next Troubleshooting