Reference

API reference

The global sofuu object: AI, HTTP, filesystem, web, memory, tools, MCP, and native modules.

Updated Nov 13, 20265 min readv0.3.0-beta
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

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

http

MethodShapeNotes
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

MethodShapeNotes
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

MethodShapeNotes
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

MethodShapeNotes
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 aboveSession working set, held in RAM until promoted or dropped.

sofuu.storage.open(path) opens a structured store with .messages, .traces, and a .kv facade.

tools

MethodShapeNotes
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

MethodShapeNotes
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

MethodShapeNotes
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 formsWires 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

BindingBehavior
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

StandardSupported primitives
Web standardsTextEncoder, TextDecoder, URL, URLSearchParams, atob, btoa, Headers, Request, Response
Web platform globalsstructuredClone, Blob/File/FormData, Event/EventTarget/CustomEvent, MessageChannel/MessagePort, navigator, persistent localStorage backed by .sofuu/localStorage.json
Web Cryptocrypto.randomUUID() from OS entropy, crypto.getRandomValues(), crypto.subtle.digest("SHA-256")
StreamsReadableStream, WritableStream, TransformStream, TextDecoderStream, TextEncoderStream; Response.body is a stable ReadableStream
node:fsreadFileSync, writeFileSync, existsSync, readdirSync, mkdirSync, unlinkSync, statSync, promises
node:pathjoin, resolve, normalize, isAbsolute, relative, dirname, basename, extname, parse, format, sep
node:bufferBuffer.from, alloc, concat, isBuffer, byteLength, toString, copy, slice
node:eventsEventEmitter with on, once, off, emit, listeners, listenerCount, setMaxListeners
node:processnextTick, version, platform, arch, versions
AI SDKsopenai, @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.