# Sofuu documentation A self-contained runtime for AI apps, tools, and agents. Start with the map, the install command, and the current beta boundaries. [Documentation home](https://docs.sofuu.xyz/) --- # Quickstart URL: https://docs.sofuu.xyz/quickstart/ Sofuu ships as one native binary. This page installs it, runs a small JavaScript program that touches memory, a native tool, and an agent definition, then packages that program as an executable. ## Before you start Sofuu publishes builds for **macOS arm64** and **Linux x86_64 / arm64**. The runtime does not need Node.js, Python, or a background daemon; the one-line installer downloads the binary for the current platform and verifies its checksum. You need a terminal and one of: - `curl` (for the install script) - Node.js and npm (for the npm install path only) The current release line is **0.3.0-beta**. Commands and APIs can change before a stable release. Keep the version you tested against in your project notes. ## Verify the install ```bash sofuu doctor ``` `doctor` prints a health check for the binary, the platform, QTSQ memory linkage, provider configuration, and model paths. Optional components can be missing and the runtime still starts; [Troubleshooting](/troubleshooting/) explains each line of the report. ```bash sofuu --version ``` ## Run a first script Create a file named `quickstart.js`: ```js // quickstart.js — memory, a native tool, and an agent definition const brain = sofuu.memory.open("./brain.qtsq", 768); brain.remember( sofuu.ai.embedLocal("runtime"), "AI runtime. One native binary.", ); // Recall in the same 768-dimension embedding space const [hit] = brain.recall(sofuu.ai.embedLocal("speed"), 1); // A native tool runs in-process behind the policy layer const sys = sofuu.tools.execute("system_info", {}); // Define an agent without needing a model to inspect its shape const agent = sofuu.agent.define({ name: "assistant", system: "Cite sources.", tools: ["coding", "memory", "web"], }); console.log(hit.text, "•", sys.platform || process.platform, "• agent:", agent.name); ``` Run it with the runtime: ```bash sofuu run quickstart.js ``` Output on macOS arm64: ```text AI runtime. One native binary. • darwin • agent: assistant ``` `sofuu.ai.embedLocal()` returns a **768-dimensional character-trigram hash**, not a trained semantic model. It is the zero-download default that makes local retrieval work without a model file or API key. `sofuu.ai.embed()` uses a different space and its default dimension is **64**, not 768. Vectors from different spaces are not interchangeable. Pick one dimension per memory file and stay in it; the [memory guide](/memory/) covers the trade-offs. ## Compile a standalone binary The same script can be packaged as a native executable: ```bash sofuu compile quickstart.js -o my-agent ./my-agent ``` The output is a single file that embeds the runtime and the script. Compiler profiles, embedded brain archives, and the supported platform matrix are covered in the [compiler guide](/compiler/). ## Next steps --- # Install URL: https://docs.sofuu.xyz/install/ Sofuu is distributed as a prebuilt native binary, not as a JavaScript package that runs on Node.js. The installer selects the archive for the current platform, verifies its checksum, and installs the `sofuu` command. The npm package downloads the native binary for the current platform. Use `npx sofuu` to run a command without a global install. ## Platform support | Platform | Architecture | Artifact | | --- | --- | --- | | macOS | arm64 (Apple Silicon) | Published build | | Linux | x86_64 | Published build | | Linux | arm64, including Raspberry Pi 5 | Published build | These are the platforms covered by published builds. Other targets require a [source build](/build/) and are not validated by the install script. ## Requirements You need a terminal and one of: - `curl`, for the one-line installer - Node.js and npm, for the npm install path only The installer and npm package do not install a model. Local vector memory and selected tools work without one; model-backed workflows need a local model and backend or a configured remote provider. ## Verify the installation Run the health check first: ```bash sofuu doctor ``` `doctor` checks that the binary starts on this platform, that the QTSQ memory archive is linked, that an encrypted store can complete a write and recall round trip, and that the context limits reported by the build are usable. The exact output varies by build and platform. Read each line: a missing optional component is not the same as failed QTSQ linkage. Then confirm the version: ```bash sofuu --version sofuu version ``` `sofuu version` prints the runtime version, commit revision (with `-dirty` when the checkout was modified), QuickJS version, and target architecture. Keep that line with any bug report. `sofuu licenses` prints the attribution report for Sofuu and the bundled third-party components. ## Checksums and direct archives Release archives ship with a SHA-256 file. To verify a downloaded archive before running it: ```bash sha256sum -c sofuu--.tar.gz.sha256 ``` Direct archives are available from the release downloads for the platforms above. Extract the archive, run the binary, and confirm it with `sofuu doctor` before replacing an existing install. If `sofuu` is not found after installation, start a new shell so the updated `PATH` is read. [Troubleshooting](/troubleshooting/) covers a missing binary, a missing model, and provider configuration. Sofuu is at **0.3.0-beta**. Command names, flags, output formats, and APIs can change between releases. Record the output of `sofuu version` in your project notes, and re-run `sofuu doctor` after upgrading. ## Where to go next --- # Build from source URL: https://docs.sofuu.xyz/build/ A source build compiles the runtime against the QTSQ memory codec, which Sofuu links as a core dependency. The process has two stages: build the QTSQ static archive, then build Sofuu with `SOFUU_QTSQ_DIR` pointing at it. ## Prerequisites | Requirement | Detail | | --- | --- | | Rust and Cargo | 1.80 or newer. Install through rustup if it is not already present. | | C and C++ toolchain | `clang` or `gcc`, plus `cmake` and `make` | | macOS headers | Xcode Command Line Tools: `xcode-select --install` | | Linux headers | `sudo apt-get install -y zlib1g-dev libcurl4-openssl-dev libssl-dev` on Ubuntu, Debian, or AWS Linux | The Linux package list covers zlib, libcurl, and OpenSSL development headers. A build that stops while linking one of those libraries usually means the corresponding package is missing. If Rust is not installed, install it through rustup: ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` ## Build the QTSQ archive Sofuu links `libqtsq.a` statically. Clone the codec, build it, and export its directory: ```bash git clone https://github.com/haruhito2666/qtsq ~/projects/qtsq cd ~/projects/qtsq make export SOFUU_QTSQ_DIR=$(pwd) ``` `SOFUU_QTSQ_DIR` must point at the directory that contains the archive produced by `make`. Export it in the same shell you use for the Sofuu build; a new terminal does not inherit it. ## Build Sofuu ```bash git clone https://github.com/sofuu-runtime/sofuu ~/projects/sofuu cd ~/projects/sofuu make deps SOFUU_QTSQ_DIR=$SOFUU_QTSQ_DIR make ``` `make deps` builds the vendored libuv. The `SOFUU_QTSQ_DIR=$SOFUU_QTSQ_DIR make` command builds the release binary and links the QTSQ archive. The resulting `sofuu` executable is in the repository root. Run `make` inside the QTSQ checkout and export `SOFUU_QTSQ_DIR`. Run `make deps`, then `SOFUU_QTSQ_DIR=$SOFUU_QTSQ_DIR make` inside the Sofuu checkout. Run `./sofuu doctor` and confirm the memory linkage and round-trip checks pass. Run `make test` before reporting a build-specific failure. ## Verify and test ```bash ./sofuu doctor make test ``` `doctor` verifies QTSQ memory linkage, a round-trip write and recall, and context limits. `make test` runs the repository test suite. If `doctor` fails on a fresh build, check that `SOFUU_QTSQ_DIR` was set for the build command, not only for the codec build. A source build reflects the current checkout, not a release tag. `sofuu version` includes the commit revision and appends `-dirty` when the working tree has modifications. Include that line when you report a build failure, so the report identifies the exact source state. ## Build constraints The QTSQ archive is linked in, but the resulting executable still uses operating system libraries such as libcurl and libssl, and model-backed workflows need a model file or a provider. A source build is not a claim that every workflow runs without external dependencies. Published builds cover macOS arm64 and Linux x86_64 and arm64. Building on another target depends on the toolchain and the libraries available there; it is not covered by the published artifact matrix. ## Where to go next --- # CLI URL: https://docs.sofuu.xyz/cli/ One binary contains the runtime, compiler, agent supervisor, MCP bridge, and plugin commands. This page groups the documented command surface by task; [Troubleshooting](/troubleshooting/) covers failure modes. ## Runtime | Command | What it does | | --- | --- | | `sofuu run ` | Executes a JavaScript or TypeScript file without a build step, on QuickJS and libuv. | | `sofuu eval ""` | Evaluates an inline JavaScript expression. `-q` suppresses output. | | `sofuu repl` | Starts an interactive JavaScript and TypeScript shell. | | `sofuu serve` | Hosts an OpenAI-compatible HTTP server for vector memory or local completions: `--brain `, `--model `, `--port 7707`. | | `sofuu capabilities --json` | Prints the runtime capability manifest: SIMD, GPU engines, transports, and enabled features. | | `sofuu doctor` | Verifies QTSQ memory linkage, a write and recall round trip, and context limits. | | `sofuu version` | Prints the runtime version, commit revision, QuickJS version, and target architecture. | | `sofuu licenses` | Prints open-source licenses for Sofuu, QuickJS, libuv, and the QTSQ memory engine. | ## Compile and package | Command | What it does | | --- | --- | | `sofuu compile ` | Packages a supported JavaScript, TypeScript, or Kaze program as a single-file executable. Takes `-o `, `--profile `, `--embed-brain `, and `--no-strip`. | | `sofuu mcp build -o ` | Compiles a supported MCP server with the micro profile. Equivalent to `sofuu compile --profile micro -o `. | Profiles, embedded archives, and the output layout are covered in the [compiler guide](/compiler/). ## Chat and sessions | Command | What it does | | --- | --- | | `sofuu chat` | Starts the terminal chat interface. Takes `-m `, `-p `, and `--sync off`. | | `sofuu session list` | Lists segmented project sessions. | | `sofuu session show ` | Shows one session and its stored state. | | `sofuu session repair` | Repairs a corrupted session manifest. | | `sofuu session prune` | Removes stale session checkpoints. | | `sofuu outputs list` | Lists archived model and tool outputs. | | `sofuu outputs search ` | Searches archived outputs. | | `sofuu outputs context ` | Builds historical task context from an archived output. | The session mesh and resume flow are described in [Chat and sessions](/chat/). ## Agents and Kaze scripts | Command | What it does | | --- | --- | | `sofuu agent run ""` | Runs a registered agent headless. `--json` emits structured output for pipelines. | | `sofuu agent init ` | Scaffolds an agent in `~/.sofuu/agents/`. | | `sofuu agent validate ` | Validates an agent definition against its schema. | | `sofuu agent list` | Lists registered agents. | | `sofuu script run ` | Executes a Kaze routine in the linear arena VM. | | `sofuu script check ` | Parses and checks a routine without running it. | | `sofuu script compile -o ` | Compiles a routine to embedded-engine bytecode. | | `sofuu script repl` | Opens the Kaze expression and policy REPL. | Standalone Kaze is at 1.0; the engine embedded in Sofuu reports 0.1. The two are not interchangeable. See the [Kaze reference](/kaze/reference/) for the standalone language. ## MCP | Command | What it does | | --- | --- | | `sofuu mcp list` | Lists servers configured in `~/.sofuu/mcp.json`. | | `sofuu mcp test ""` | Tests the handshake, protocol negotiation, and tool count. | | `sofuu mcp inspect "" --call --args ''` | Inspects tool schemas and invokes one tool directly. | | `sofuu mcp link cursor` | Writes server configuration into Cursor settings. | | `sofuu mcp link claude-desktop` | Writes server configuration into Claude Desktop settings. | An external server launched through `npx` keeps its own dependencies and install requirements. ## Memory, policy, and plugins | Command | What it does | | --- | --- | | `sofuu brain stats` | Reports statistics for a QTSQ memory file. | | `sofuu brain verify ` | Verifies a memory container. | | `sofuu brain backup` | Backs up a memory container. | | `sofuu brain restore` | Restores a memory container. | | `sofuu brain repair` | Repairs a memory container. | | `sofuu policy check` | Validates policies in `.sofuu/policy.json`. | | `sofuu policy why [args]` | Explains an allow or deny decision. | | `sofuu plugin list` | Lists plugins and circuit-breaker states. | | `sofuu plugin add ` | Installs a provider plugin. | | `sofuu plugin init ` | Scaffolds a plugin. | | `sofuu plugin validate ` | Validates plugin schemas and registration. | | `sofuu plugin test ` | Runs a plugin tool and reports its circuit state. | Plugins run in-process and must be trusted as code. Their checks are not an operating system sandbox. ## Logs and recovery | Command | What it does | | --- | --- | | `sofuu logs` | Lists recent runs with run ID, start time, step count, and exit status: `DONE`, `ERROR`, or `CANCELLED`. | | `sofuu logs show ` | Renders the event trace for model calls, tool executions, and step summaries. | | `sofuu logs --follow` | Streams tokens and tool calls from an active background worker. | | `sofuu logs --last-error` | Prints the failure context, stack trace, and post-mortem card for the newest failure. | | `sofuu resume ` | Attempts to resume a run from its last durable checkpoint. Checkpoints altered by redaction or truncation are refused. | ## Preview commands These commands are marked preview in the current docs and may change: | Command | What it does | | --- | --- | | `sofuu dev [dir] --port 3000` | Reactive dev server with a streaming JSX and TSX transpiler. | | `sofuu infer [prompt]` | Local CPU inference over GGUF or SafeTensors files. | | `sofuu swarm worker` | Distributed transformer layer pipelining over LAN sockets. | | `sofuu drone status` | MAVLink v2 telemetry and hardware safety gates. | ## Common workflows ### Iterate on a script, then package it ```bash sofuu run app.js sofuu compile app.js -o dist/app ./dist/app ``` The first command runs from source. The second appends the compiled payload to a base runtime; the output is a single executable for the current platform. ### Check a Kaze routine, then compile it ```bash sofuu script check agent.kaze sofuu script run agent.kaze sofuu script compile agent.kaze -o agent.kazebc sofuu compile agent.kaze -o dist/kaze-agent ``` `script check` parses and checks without executing. `script compile` emits embedded-engine bytecode, while `sofuu compile` packages a supported routine as a standalone executable. ### Trace a failed agent run ```bash sofuu agent run auditor "Audit src/" sofuu logs sofuu logs --last-error sofuu resume ``` If the run failed, `--last-error` produces the post-mortem card. `resume` only proceeds when it finds a usable checkpoint. ### Test and publish an MCP server ```bash sofuu mcp list sofuu mcp test "npx -y @modelcontextprotocol/server-filesystem /tmp" sofuu mcp build server.ts -o dist/my-mcp-server ./dist/my-mcp-server ``` `mcp test` checks the handshake before you depend on the server. `mcp build` uses the micro profile to keep the artifact minimal. --- # Compiler URL: https://docs.sofuu.xyz/compiler/ `sofuu compile` packages a supported JavaScript, TypeScript, or Kaze program as a single-file native executable. It does not invoke an external linker or archive packager: the compiler appends the program payload to a base runtime and writes one file. ## Profiles The profile selects the base runtime. Pick the smallest one that contains the APIs your program calls. | Profile | Flags | Base | Includes | Use when | | --- | --- | --- | --- | --- | | Micro | `--profile micro`, `--micro`, `--mcp` | `sofuu-micro` | Minimal QuickJS, libuv, and the micro-runtime surface for MCP servers and single-purpose tools. | MCP servers, single-purpose tools, microservices. | | Lean (default) | `--profile lean`, `--lean` | `sofuu-agent` | Full QuickJS, libuv, vector memory, sandboxed tools, policy gates, and the agent loop. Drops the local GGUF engine and CLI developer subcommands. | Agents, background daemons, CLI tools, edge workers. | | Full | `--profile full`, `--full`, `--with-inference` | `sofuu` | The complete runtime, including local GGUF inference, raw model loaders, dev servers, robotics, and all CLI subcommands. | Offline applications that embed their own weights. | Omit the profile to get lean. Sizes vary by platform and profile, so measure the artifact you build rather than relying on a fixed number. ## Flags | Flag | Effect | | --- | --- | | `-o ` | Output path. Defaults to the entry file name without its extension. | | `--profile ` | Selects `micro`, `lean`, or `full`. | | `--embed-brain ` | Packs an encrypted QTSQ memory container into the executable. | | `--no-strip` | Preserves debugging symbols in the output. | | `--base ` | Uses a custom base executable instead of a built-in profile base. | ## Examples ```bash # Lean profile: agents, memory, tools sofuu compile agent.js -o dist/my-agent # Micro profile: a small tool or MCP server sofuu compile agent.js --profile micro -o dist/tool # Embed a prebuilt memory archive sofuu compile agent.js --embed-brain ./brain.qtsq -o dist/agent-with-memory # Package a Kaze routine sofuu compile agent.kaze -o dist/kaze-agent ``` The output runs directly: ```bash ./dist/my-agent ``` ## Embedded memory `--embed-brain` packs the entire `.qtsq` container, including its manifest and segment directory, into the executable. On first launch the archive is extracted beside the binary if it is absent, and the mounted path is exposed as `sofuu.memory.embedded`. The archive must already exist before you compile; create and populate it with the memory API covered in the [memory guide](/memory/). ## MCP servers `sofuu mcp build` is a shortcut for the micro profile: ```bash sofuu mcp build server.ts -o dist/my-mcp-server ``` It is equivalent to: ```bash sofuu compile server.ts --profile micro -o dist/my-mcp-server ``` The compiled server is one file, but an external server it launches still needs its own runtime and dependencies. ## Signing on macOS Appending data to a signed Mach-O binary invalidates the signature, and macOS kills the process. The compiler strips the old signature, extends the `__LINKEDIT` segment over the payload, and applies an ad-hoc `codesign -s - -f` signature. That signature is local, not a distribution identity. Linux needs no such step: the kernel loader reads payload data after the ELF boundary. Recompiling replaces the previous payload rather than nesting another. ## What the output contains ```text base runtime executable bundled dependency graph, TypeScript stripped precompiled QuickJS bytecode optional QTSQ brain archive 32-byte trailer: SOFUU_BIN_V1, version, flags, payload length, CRC32 ``` At startup the binary looks for the trailer. When present, it verifies the payload checksum, loads the bytecode, mounts an embedded brain, maps arguments to `process.argv` and `sofuu.args`, and runs the program. Without a trailer it behaves as the normal `sofuu` CLI. `SOFUU_PLAIN=1` forces that CLI path for inspection: ```bash SOFUU_PLAIN=1 ./dist/my-agent doctor ``` ## Constraints Only supported programs compile. Programs outside that surface are not guaranteed to build or run, and there is no general bundling guarantee for arbitrary npm trees. Compiled artifacts may still link OS libraries such as libcurl and libssl, and model-backed workflows still need a model file, backend, or provider. A separate Node.js or Python installation is not needed for supported code, but the operating system and network remain. Published builds cover macOS arm64 and Linux x86_64 and arm64. Recompile on the target platform when you need a binary for a platform outside that matrix. Supported Kaze routines receive compile-time checks and a compiled agent selects an entry routine when unambiguous. Authorized model-and-tool calls have been exercised on selected local debug-build paths; unavailable backends fail. Published artifacts, other providers and physical hardware require separate verification. Standalone Kaze is at 1.0. The engine embedded in Sofuu reports 0.1, so the two are not interchangeable. Use the [Kaze reference](/kaze/reference/) for standalone behavior and treat compiled Kaze agents as preview until the shared contract lands. ## Where to go next --- # Chat & sessions URL: https://docs.sofuu.xyz/chat/ `sofuu chat` is the terminal chat interface: streamed answers, a built-in tool belt, encrypted local memory, and a coordination layer for several sessions working in one project. ```bash sofuu chat ``` | Flag | Effect | | --- | --- | | `-m ` | Starts with a specific model. | | `-p ` | Starts with a specific provider. | | `--sync off` | Disables the project session mesh for this session. | ## Model backend Chat answers come from a configured model backend. A local backend needs its model files; a remote provider needs credentials and network access. Inside a session, `/provider` and `/model` switch between backends that are already configured. Chat state, memory, and provider configuration are separate. Changing the chat model does not change the embedding space of an existing memory file. A missing provider key is a configuration problem rather than a chat problem; [Troubleshooting](/troubleshooting/) covers the provider and model paths. ## The tool belt The built-in tools are `read_file`, `write_file`, `edit_file`, `grep`, `glob`, `list_dir`, and `bash`. `/tools` toggles the belt on or off for the session. Built-in tools execute with the permissions of the user running Sofuu. The tool belt is not an operating system sandbox, and toggling it does not change file permissions. Review commands that write outside the project. ## Project session mesh When several terminal sessions run against the same project, `sofuu chat` synchronizes active tasks, notes, alerts, and shared context through bounded project storage. The mesh carries that coordination state, not file contents. Use `/work` to claim a task before editing, `/note` for information another session should see, and `/notify` when a peer needs to stop and look. `/context` attaches shared context to the current session. Start with `--sync off` when you want a session isolated from the mesh. ## Slash commands | Command | Purpose | | --- | --- | | `/work ` | Broadcasts the active task so other sessions avoid conflicting work. | | `/done` | Marks the active task complete and clears work status across the mesh. | | `/note ` | Saves a note visible to all sessions on the project. | | `/notify ` | Emits a high-priority banner to connected peer sessions. | | `/context [id]` | Inspects or attaches shared context across project sessions. | | `/remember ` | Pins a durable fact or architecture rule into the local encrypted QTSQ brain. | | `/compact` | Compacts conversation history when the context window fills, preserving questions and decisions. | | `/ctx` · `/cost` | Live context-window and spend meters. Accepts `1m`, `128k`, or raw token counts. | | `/effort ` | Sets reasoning effort: `low`, `medium`, `high`, or `max`. | | `/provider` | Switches the LLM backend. | | `/model` | Switches the model. | | `/tools` | Toggles the active tool belt. | | `/sessions` | Lists past project sessions. | | `/resume` | Resumes a run by ID. | | `/help` | Prints the interactive command documentation. | ## Sessions and checkpoints `/sessions` lists the sessions stored for the project. The CLI exposes the same state: ```bash sofuu session list sofuu session show sofuu session repair sofuu session prune ``` `repair` addresses a corrupted manifest. `prune` removes stale checkpoints. Both operate on stored session state rather than on project files. Agent runs write durable checkpoints as they proceed. After an interruption or failure, `sofuu resume ` attempts to continue from the last usable checkpoint: ```bash sofuu resume ``` Resume is conditional. A checkpoint changed by redaction, or truncated at a known boundary, is refused rather than replayed with missing state. Not every interrupted run can be resumed. ## Logs | Command | Output | | --- | --- | | `sofuu logs` | Recent runs with run ID, start time, step count, and exit status (`DONE`, `ERROR`, `CANCELLED`). | | `sofuu logs show ` | Human-readable trace of model calls, tool executions, and step summaries. | | `sofuu logs --follow` | Live tokens and tool calls from an active background worker. | | `sofuu logs --last-error` | Failure context, stack trace, and post-mortem card for the newest failure. | `--last-error` shows why a run stopped before you decide whether to resume it or start over. Redaction recognizes known patterns rather than every possible secret. Crash cards are generated on a best-effort basis and can be unavailable. Logs, exported outputs, and external providers each have their own data handling. Errors use a versioned diagnostic shape with a stable code, severity, location, reason, and bounded hints. ## Where to go next --- # Plugins URL: https://docs.sofuu.xyz/plugins/ Plugins extend the runtime with tools, inference providers, stores, and lifecycle services. They load from the project directory, the user config directory, or a manifest, and tool calls pass through one validation and policy pipeline regardless of where the plugin came from. Plugins run **in-process** in the same runtime as your application. The schema, policy, timeout, circuit-breaker, and watchdog checks described here contain faults; they are not an operating-system sandbox and do not contain malicious code. Treat every third-party plugin the way you treat any third-party dependency. ## What a plugin can register | Factory | Category | Registers | | --- | --- | --- | | `defineTool` | Tool | A callable with a declared schema, permissions, timeout, and breaker. | | `defineProvider` | Inference provider | A `complete` or `stream` implementation for a model backend. | | `defineStorage` | Key/value store | `get`, `set`, `delete`, `keys`, plus `flush` and `stats`. | | `defineVectorStore` | Vector store | `upsert`, `query`, `delete`, and `count`. | | `defineService` | Lifecycle service | Hooks for start, turn start, tool call, tool result, turn end, and stop. | | `useOpenAPI` / `ingestMcp` | Bridge | Tools generated from an OpenAPI document or an existing MCP server. | A file registers itself with `export default defineTool(...)`, or by calling another factory directly. A file that loads but registers nothing is reported as **broken**; it does not abort discovery of the remaining plugins. ## Define a tool ```ts // plugins/weather.ts export default defineTool({ name: "weather", description: "Get current weather for a city", schema: z.object({ city: z.string() }), timeoutMs: 5000, permissions: { net: ["api.weatherapi.com"] }, // network allowlist circuitBreaker: { failureThreshold: 5, resetTimeoutMs: 30000 }, async run({ city }, ctx) { const res = await ctx.fetch( `https://api.weatherapi.com/v1/current.json?q=${city}`, ); return res.json(); }, }); ``` | Field | Purpose | | --- | --- | | `name`, `description` | Identity shown in the tool inventory and to the model. | | `schema` | Input contract. Accepts the bundled micro-Zod subset or a plain JSON Schema object. | | `output` / `resultSchema` | Optional output contract. A soft failure (`{ok:false}`) passes through untouched. | | `permissions.net` | Host allowlist applied by the guarded `ctx.fetch`. | | `requiresApproval` | Risk hint surfaced to the host approval UI. | | `timeoutMs` | Watchdog deadline. The default is 15 seconds. | | `circuitBreaker` | Failure threshold and reset window. The default is 5 failures in 30 seconds. | | `run(args, ctx)` | The implementation. Every call receives the validated arguments. | `ctx` provides a guarded `fetch`, a filesystem jail scoped to the session root (`readFile`, `writeFile`, `exists`, `readdir`, `mkdir`, `rm`, and related helpers), an abort signal tied to the watchdog, a read-only environment snapshot, and prefixed logging. A blocked host raises `E_DENIED`, and the tool returns `{ok:false, source:'plugin', error:{code,message}, text}`. ## Discovery and loading | Source | Path | Notes | | --- | --- | --- | | Project | `./plugins/*.{js,ts}` | Dotfiles and `*.d.ts` are ignored. | | User | `~/.sofuu/plugins/*.{js,ts}` | Applies to every project. | | Manifest | `sofuu.json` | `plugins: [{ source, enabled? }]`; `source` is a path, never a fetched URL. | TypeScript is stripped textually and then evaluated. There is no separate `tsc` step, and the stripper is not `tsc`: decorators, `abstract`, `implements`, overload signatures, and some annotated class forms are not transformed. Write the plain-JavaScript equivalent for those, and run `sofuu plugin validate` before relying on discovery. ```bash sofuu plugin init weather --category=tool sofuu plugin list # name, category, circuit state, timeout sofuu plugin validate plugins/weather.ts sofuu plugin test weather '{"city":"Guwahati"}' sofuu plugin add llamacpp # install from the provider catalog ``` ## The execution pipeline Every tool call passes through the same ordered shields. | # | Shield | Failure code | Behavior | | --- | --- | --- | --- | | 1 | Input schema | `E_SCHEMA` | Validated before `run()`; the callable never sees a bad argument. | | 2 | Policy and network | `E_DENIED` | Checked before execution. `ctx.fetch` and `ctx.fs` add their own checks. A denial does not trip the breaker. | | 3 | Circuit breaker | `E_CIRCUIT_OPEN` | Opens after the configured failures. In half-open state, one trial is admitted at a time. | | 4 | Watchdog | `E_TIMEOUT` | Delivers an abort to `ctx.signal` at `timeoutMs`. | | 5 | Panic guard | `E_TOOL` | Synchronous throws, rejected promises, circular returns, and BigInt results become typed results. | The policy check denies when evaluation is unavailable, malformed, or fails. `sofuu.plugins.invoke` reads the evaluator's actual `ask` decision and requests approval when required, or accepts explicit host approval; an unattended `ask` is denied. A policy denial overrides a supplied approval. A host that calls the lower-level `execute` path directly must handle `ask` itself. The typed-denial paths are covered by unit and integration tests, including allow, deny, deny-before-approval, and explicit approval. Unavailable, throwing, and malformed evaluators have not been exercised against a real failing host, and other tool surfaces were not assessed. Do not read this pipeline as proof of coverage for every execution path. ## Limits before you ship - Plugin code runs in-process. The shields contain faults, not malice; a plugin that allocates without bound can still hurt the process. - Provider streams from JavaScript adapters are buffered and then replayed, not delivered incrementally. A body over 8 MB fails with `E_BACKPRESSURE`. - `useOpenAPI` generates one tool per operation but does not implement authentication flows. Pass headers through `opts.headers` and keep secrets in the environment. - `useOpenAPI` and `ingestMcp` never fetch a remote document. You supply the spec text or the server command. ## Next steps --- # Model Context Protocol URL: https://docs.sofuu.xyz/mcp/ Sofuu includes a native Model Context Protocol client and server; no external SDK is required inside the runtime. The client connects to local or remote servers, and the server exposes tools, resources, and prompts over stdio, HTTP, or an in-process transport from the same JavaScript surface. Sofuu is **0.3.0-beta**. MCP method names, transports, and configuration keys can change before a stable release. The `docs/MCP.md` reference in the source tree is the authority for the surface described here. ## Client ```js // stdio: a command string, or {command, args, env, cwd} const client = await sofuu.mcp.connect( "npx -y @modelcontextprotocol/server-filesystem /tmp", ); // Streamable HTTP const httpClient = await sofuu.mcp.connect({ url: "http://127.0.0.1:9000/mcp", transport: "http", // "auto" also selects Streamable HTTP }); const tools = await client.listTools(); const result = await client.call("read_file", { path: "/tmp/data.txt" }); // The raw MCP result is normalized by the same mapper the agent loop uses. console.log(sofuu.tools.mcpResult(result).text); client.disconnect(); ``` `client.listTools()` and `client.listResources()` follow `nextCursor` until the inventory is complete. A repeated cursor, or more than 32 pages, stops the walk instead of looping. `client.protocolVersion()` reports the version the server negotiated, and `client.onNotification(handler)` receives server notifications such as `notifications/tools/list_changed`. `client.call(method, params, { timeoutMs })` accepts a bare tool name, which is wrapped into `tools/call`, or a protocol method such as `ping`, which is sent verbatim. On a stdio deadline the client sends `notifications/cancelled` and frees the pending slot. Cancellation does not prove the server stopped. After a potentially effectful request has been dispatched, a lost reply or deadline is reported as `E_MCP_OUTCOME_UNKNOWN`; check the real effect before retrying. Requests that time out while still queued for reconnection were never dispatched. Reconnection rechecks the server policy before starting a new transport, and a denied or unavailable policy rejects queued calls. ## Transports and protocol versions | `transport` | Behavior | | --- | --- | | `stdio` (default) | Spawns a command and speaks newline-delimited JSON-RPC over stdin/stdout. | | `direct` | Connects an in-process server object to a client without process spawning. A direct client can be passed to `agent.define({ tools: [directClient] })`. | | `http` / `auto` | Streamable HTTP: POST JSON-RPC, carry `Mcp-Session-Id`, accept JSON or SSE response bodies, and DELETE the session on disconnect. | | `sse` | Legacy HTTP+SSE: GET the URL as an event stream, read the `endpoint` event, then POST messages to that URI. | The client offers protocol version `2025-06-18`, and `protocolVersion()` returns the server's choice. A bare `{url}` means Streamable HTTP; the client never infers legacy HTTP+SSE from a URL. Under `transport: "http"` or `"auto"`, a legacy endpoint is a typed refusal rather than a silent downgrade. Request `transport: "sse"` explicitly to use the legacy transport, which carries protocol `2024-11-05`. The server's `initialize` negotiates `2025-06-18` or `2024-11-05` and advertises only the capabilities it implements. A server can also answer `ping`, and server-to-client requests are handled: `roots/list` answers with the policy `fs.roots`, and an undeclared request is answered with `-32601`. ## Configuration `sofuu.mcp.loadConfig()` is the loader for `~/.sofuu/mcp.json`; `SOFUU_MCP_CONFIG` overrides the path. The file is a JSON array: ```json [ { "name": "fs", "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"], "env": { "TOKEN": { "secret": "MCP_TOKEN" } }, "cwd": "/tmp", "enabled": true, "tools": { "allow": ["read_file"], "deny": ["write_file"] } } ] ``` A remote entry supplies `url` and an optional `transport` (`"http"` by default, or `"sse"`); `command` then becomes optional. A missing file means no servers. A corrupt file is reported as `{ok:false}` and left in place, never silently overwritten. The child environment stays the functional allowlist: `env` can add or remove names, never inherit everything, and `null` removes a name. A `{"secret":"NAME"}` value is resolved at spawn time through `policy.secret`; the config and loader see only the name, and a missing secret refuses the connect. `tools{allow,deny}` filters the inventory before names are assigned, and deny wins. A filtered tool cannot claim a name slot or reach the model. A tool whose name collides with a builtin or inline tool is exposed as `__` instead of shadowing the existing tool. ## Server ```js const server = sofuu.mcp.serve({ name: "math-service", version: "1.0.0" }); server.tool( "add", { description: "Add two numbers", schema: { type: "object", properties: { a: { type: "number" }, b: { type: "number" } }, required: ["a", "b"], }, }, ({ a, b }) => ({ result: a + b }), ); server.resource( "note://hello", { name: "Hello", mimeType: "text/plain" }, () => "HELLO", ); server.prompt("greet", { description: "A greeting" }, ({ name }) => `Hello ${name}`); server.start(); // stdio on fd 0/1 // server.stop(); // idempotent; close() is an alias ``` `server.tool`, `server.resource`, `server.prompt`, `server.start`, and `server.stop` are the registration and lifecycle surface. `server.use(fn)` adds middleware in onion order, running on both tools and requests. `initialize` negotiates the client's protocol version, and `ping` answers `{}`. `tools/list`, `resources/list`, and `prompts/list` paginate at 50 entries per page. `resources/read` and `prompts/get` route to their handlers, which must be **synchronous**; an async resource or prompt handler is a typed error. A throwing or rejecting tool handler answers in-band with `{content:[{type:'text',text}], isError:true}`, not a JSON-RPC error. Object results also carry `structuredContent`, with a text mirror kept. Registering a tool after the first `tools/list` emits `notifications/tools/list_changed`. An HTTP server mode is available with `sofuu.mcp.serve({ transport: "http", port: 19842 })`; `close()` stops it. ## Build a standalone server ```bash sofuu mcp build server.ts -o dist/my-server sofuu mcp inspect ./dist/my-server --call add --args '{"a":1,"b":2}' ``` The build targets the dedicated micro-runtime base and can remove unused subsystems. A supported server binary does not need a separate Node.js or Python installation, but OS libraries and services used by the server may still be required. Measure startup, memory, and size for your own binary rather than assuming a fixed footprint. ## CLI | Command | Purpose | | --- | --- | | `sofuu mcp list` | Lists configured servers from `~/.sofuu/mcp.json`. | | `sofuu mcp test ""` | Tests the handshake, protocol negotiation, and tool/resource counts. | | `sofuu mcp inspect "" --call --args '{...}'` | Inspects schemas and invokes a tool directly. | | `sofuu mcp add`, `sofuu mcp remove` | Validate before writing, then replace the file atomically. | | `sofuu mcp init ` | Scaffolds a new server with an idiomatic schema. | | `sofuu mcp build -o ` | Compiles a standalone micro-server. | | `sofuu mcp link cursor` | Synchronizes server definitions into the target client. | ## Trust boundaries Sofuu applies per-server tool allow/deny filters and `net.allow` / `net.deny` policy to the URL host, but the server's own implementation is outside the runtime and is not covered by its policy gates. A remote server receives the arguments of every tool you call and may perform effects you did not intend. Review the server before enabling it, and keep `tools.deny` narrow. Approval has a known gap at this boundary: tool calls that require `approval.mode: "always"` currently fail closed with `E_POLICY_APPROVAL_REQUIRED`. An agent approval is not yet carried as a verifiable receipt to the MCP dispatch boundary, so the call is refused rather than run without proof. `sofuu.tools.mcpResult(result, meta)` is the single mapper used by the agent loop. It normalizes every content block, `structuredContent`, and `isError` into the uniform tool contract `{ok, text, data?, error?, meta}`. MCP `annotations` (`readOnlyHint` and `destructiveHint`) steer the approval risk flag. ## Next steps --- # Memory URL: https://docs.sofuu.xyz/memory/ `sofuu.memory` is the on-device vector memory surface, backed by QTSQ containers (`.qtsq`). A container stores records with vectors, text, timestamps, and roles, and it is encrypted by default. Sofuu is **0.3.0-beta**, so method shapes may change. Memory is encrypted by default with a machine-local key. Plaintext mode is explicit, and exports are not encrypted. Decide which mode your application needs before writing data you cannot recreate. ## Open a container ```js const brain = sofuu.memory.open("./brain.qtsq", 768); ``` `open(path, vecDim, options?)` opens an encrypted QTSQ container. An object form (`{ path, dim, space }`) is also accepted. The third positional argument can carry open modes such as `{ readonly: true }`, `{ verifyFull: true }`, or `{ plaintext: true }`. | Method | Behavior | | --- | --- | | `open(path, vecDim, options?)` | Opens a container and returns a handle. | | `remember(vectorOrText, text?, role?, turn?)` | Stores a record with a vector, timestamp, and text. A plain string is embedded automatically. | | `recall(queryVectorOrText, k)` | Returns the top `k` nearest records, including `distance` (0 is an exact match) and `similarity`. | | `count()` / `stats()` | Total records, active segments, and capacity metrics. | | `flush()` | Persists pending writes to the container. | | `forget(index)` | Removes a record by its index. | | `list(options?)` | Returns records, with optional `tier`, `role`, `entity`, `text`, `min_strength`, `offset`, and `limit` filters. | | `export()` | Produces an export of the container. Exported copies are not encrypted. | | `close()` | Releases the handle. | Open containers are also addressable by a small handle object, which is what the C funnel uses. Close a container with `close()` when you are done with it. ## Remember and recall ```js const text = "Sofuu embeds a JavaScript runtime in one native binary."; brain.remember(sofuu.ai.embedLocal(text), text, "user"); const hits = brain.recall(sofuu.ai.embedLocal("single binary"), 3); for (const hit of hits) { console.log(hit.text, hit.distance, hit.similarity); } brain.flush(); brain.close(); ``` Keep one embedding space per container. A write from a different space is refused with a typed error rather than silently corrupting recall. ## Embedding spaces | Space | Dimensions | Notes | | --- | --- | --- | | `hash-768` | 768 | Default for `sofuu.ai.embedLocal()` and for the brain. A character-trigram hash with zero parameters. | | `sem1-64` | 64 | Opt-in learned space. | | `sem2-64` | 64 | Opt-in learned space, and the default for `sofuu.ai.embed()`. | | `img1-64` | 64 | Image projector, compatible with `sem2-64` text geometry. | `sofuu.ai.embedLocal()` returns a **768-dimensional character-trigram hash**. It is not a trained semantic model; it is the zero-download default that makes retrieval work without a model file or API key. `sofuu.ai.embed()` uses a different space, with a default dimension of **64** (`sem2-64`). Vectors from different spaces are not interchangeable. A 768-dimensional vector cannot be compared with a 64-dimensional one, and mixing spaces in one index is a correctness error. The spaces are tagged by model and dimension. `img1-64` is the one documented exception: it is jointly trained with `sem2-64` text geometry, so text queries can retrieve images. Every other index uses one space. ## Encryption and keys QTSQ containers use AES-256-GCM with a machine-local key. The key resolution order is: 1. `SOFUU_BRAIN_KEY`, supplied as 64 hex characters (32 bytes). 2. `~/.sofuu/brain.key`, 32 random bytes written as hex with mode `0600` and created on first use. 3. If no usable key exists, a process-local random key is used and the reason is printed. Brains written in that process will not reopen. The key is read once per process and cached. Losing the key file means the brain file is unreadable; there is no recovery path in the runtime. Copy the key if the brain matters. A brain copied to another machine will refuse to open unless the key moves with it. This is at-rest protection, not a sandbox. Anything running as your user can read the key and decrypt the brain, and a compromised machine has the same access. Plaintext mode is explicit: `sofuu.memory.open("./notes.qtsq", 768, { plaintext: true })`. It is useful for inspection and tests, not for data you would not put in a plain file. Logs and external providers have their own data handling, separate from the brain. ## Working memory A session working set holds records that are not yet durable. It uses the same vector shape as the main store. ```js brain.rememberWorking(vec, "candidate fact", "user"); brain.promoteWorking([id]); // move selected records into the durable store brain.clearWorking(); ``` | Method | Behavior | | --- | --- | | `rememberWorking(vec, text, role?)` | Adds a record to the session working set. | | `promoteWorking(ids)` | Promotes the selected records into the durable store. | | `clearWorking()` | Drops the working set without promoting it. | These methods are available through JavaScript and the C funnel (`memory.rememberWorking`, `memory.promoteWorking`, `memory.clearWorking`). ## Remote adapters Remote vector backends are opt-in. They are not the default path, and they require network access plus a reachable service. ```js const remote = sofuu.memory.open("https://qdrant.example.com", { adapter: "qdrant", // qdrant | pinecone | pgvector | custom dimensions: 768, collection: "notes", apiKeyEnv: "QDRANT_API_KEY", }); await remote.remember("hello", { tags: ["note"] }); const hits = await remote.recall({ query: "hello", limit: 5 }); ``` The adapter keeps the same `remember` / `recall` contract, but its calls are asynchronous. `apiKeyEnv` names an environment variable rather than passing the key in the call. A custom adapter object with `remember` and `recall` methods is also accepted. Keep a remote index on one space, as you would a local container. ## Related storage `sofuu.storage.open(path)` opens a structured store with `.messages`, `.traces`, and a key-value facade at `.kv`. Use it for message records and run traces; use `sofuu.memory` for vector recall. The two are separate files with separate lifecycles. ## Next steps --- # Agents & tools URL: https://docs.sofuu.xyz/agents/ `sofuu.agent` defines and runs the agent loop: a named definition, a task, a tool set, a budget, and a trace. Runs can be cancelled, listed, and inspected, and every tool call passes through validation and policy before it executes. An agent can call tools repeatedly until its budget is exhausted or it stops. Set `budget.maxSteps` and `budget.maxWallMs` deliberately, and decide the `approve` mode before the first run. A denial is returned to the model in-band as `denied by user`, so the run continues instead of crashing. ## Define an agent ```js sofuu.agent.define({ name: "researcher", system: "You research accurately. Cite sources with URLs.", tools: ["web", "memory", "system"], memory: "agent", approve: "sensitive", budget: { maxSteps: 12, maxWallMs: 120_000 }, }); ``` `define(def)` registers a definition and returns a handle. `run` also accepts a definition object directly. | Field | Meaning | | --- | --- | | `name` | Required registry name. | | `system` | The system prompt carried by the definition. | | `tools` | Tool names, domain packs, inline tool objects, or connected MCP clients. | | `memory` | `"shared"`, `"agent"`, or `"off"`. Scopes over one physical brain file. | | `provider`, `model` | Optional per-agent backend selection. | | `budget` | `maxSteps`, `maxDepth`, `maxTokens`, and `maxWallMs`. | | `approve` | `"none"`, `"sensitive"`, or `"all"`. | | `agents` | Names of sub-agents this definition may delegate to. | | `rlm` | `"auto"`, `"on"`, or `"off"` for long-context routing. | | `identity` | Optional `{ role, expertise }` metadata. | Definitions live in memory and can also be loaded from `~/.sofuu/agents/*.js` with `sofuu.agent.loadDir()`. Those files are trusted scripts: they execute in global scope like any other user script. ## Run, cancel, and inspect ```js const result = await sofuu.agent.run( "researcher", "Compare ARM NEON and AVX2", ); console.log(result.answer); console.log(result.stopped, result.usage); ``` `run(handleOrNameOrDef, task, opts)` returns a promise. Options include `context`, `history`, `signal`, `onStep`, `onApproval`, `toolTimeoutMs`, and per-run provider or model overrides. | Result field | Meaning | | --- | --- | | `answer` | Final text produced by the run. | | `steps` | Step records for the run. | | `subRuns` | Nested runs started by delegation. | | `usage` | Token usage accumulated across the run. | | `trace` | The structured event trace. | | `stopped` | Why the run ended, including cancellation. | | `runId`, `name` | Identity of the run and its definition. | `sofuu.agent.cancel(id)` marks the run cancelled and fires its abort handlers; it returns `false` when the id is not active. `sofuu.agent.list()` returns registry summaries with tool counts, MCP server counts, sub-agents, and 24-hour run counts. `sofuu.agent.renderTrace(result)` renders the trace as text for logs or host display. `sofuu.agent.runMany()` and `sofuu.agent.mapContext()` are available for concurrent runs and context reduction. ## Tools | Source | How it is added | | --- | --- | | Inline tools | An object with `name`, `description`, `parameters`, and `execute(args)`. | | Domain toolpacks | A pack name such as `"coding"`, `"web"`, `"memory"`, or `"system"`. | | MCP | A connected client in `tools`, or a server configured in `~/.sofuu/mcp.json`. | | Plugins | Tools registered by `defineTool`, subject to the plugin pipeline. | | Host tools | Native tools registered through the C ABI. | | Pack | Tools | Notes | | --- | --- | --- | | `coding` | `read_file`, `write_file`, `edit_file`, `apply_patch`, `grep`, `glob`, `list_dir`, `bash`, `code_eval`, `todo_write` | Filesystem tools use the project jail. `SOFUU_NO_SHELL=1` removes `bash`. | | `web` | `web_search`, `web_open` | Keyless search and readable page fetching. | | `memory` | `memory_search`, `memory_remember` | Recall and persist against the local QTSQ brain. | | `system` | `system_info` | Runtime version, platform, CPU, GPU engine, RAM, and capabilities. | Non-coding agents receive no coding tools by default. Agents opt in with a pack, individual tool names, or `"all"`. ## Policy and approvals Validation runs before permission, policy, and execution. A bad argument returns `E_SCHEMA` and the tool never runs. The coding reader jail checks both the lexical path and the real path, and refuses a symlink inside the project that points outside it. `bash` is filtered by `SOFUU_NO_SHELL`, `tools.deny`, `shell.enabled`, and `shell.allow`; an allowlist judges every chain segment, not just the first command. `sofuu.tools.list()` reports each tool's `policy.allowed` and `requiresApproval` flags, so a host can render the same inventory the model sees. Agent-level `netPolicy` matches the URL host only, and the infrastructure SSRF guards remain underneath it. Approval decisions follow the definition and the active policy: - `approve: "sensitive"` prompts for tools outside the read-only auto-pass set; `"all"` prompts for every tool; `"none"` relies on policy. - `opts.onApproval(tool, args)` or the host approval channel decides. The loop emits `approval_request {id, tool, args, risky, mode}`. - Policy is authoritative over the definition. `approval.mode: "always"` prompts even for `approve: "none"` and bypasses the session cache; `"never"` suppresses the gate; a deny always wins. Each decision emits a `policy` event with a rule id. - A missing answer, a callback error, a cancellation, or the tool timeout all deny. An `always` grant applies only to the rest of that run, and bash grants are command-scoped. Hosts that park prompts can settle them explicitly: ```js const pending = sofuu.agent.pendingApprovals(); // [{ id, tool }] const settled = sofuu.agent.resolveApproval(pending[0].id, true, false); ``` `resolveApproval(id, allow, always)` returns `{ok:true}` or `{ok:false, error}`. The same two operations are exposed through the C funnel as `agent.pendingApprovals` and `agent.resolveApproval`. ## Sandbox and enforcement limits `sofuu.sandbox.run(source, options)` evaluates JavaScript or TypeScript in a separate QuickJS runtime with its own heap and intrinsics. ```js const result = await sofuu.sandbox.run(source, { preset: "standard", fuel: 20_000_000, timeoutMs: 10_000, maxMemoryMB: 64, }); ``` | Preset | Workload | Deadline | Fuel | Memory | | --- | --- | --- | --- | --- | | `strict` | Untrusted model-generated code | 2 s | 5M instructions | 32 MB | | `standard` | Developer scripting | 10 s | 20M instructions | 64 MB | | `compute` | Math, simulations, ETL | 300 s | unlimited | 512 MB | | `worker` | Long-running background work | none | unlimited | 256 MB | The result carries `success`, `result`, `errorType`, `code`, `fuelUsed`, `elapsedMs`, and captured `logs`. A deadline violation carries `E_TIMEOUT`. The sandbox is a separate runtime with no host globals, no I/O, no process, no module system, no subprocess, and no route to `sofuu.*` unless you bridge a value into `globals`. It is **not** a defence against native extensions (there are none), a multi-tenant scheduler, or a module loader. It also cannot interrupt a bridged host function that blocks; the deadline meters sandbox execution, not the host callback. Tool policy applies at the tool-call boundary. Code inside the sandbox does not inherit the host tool inventory or its policy decisions unless you bridge a function that performs those calls. Plugins remain in-process and are not made safe by the sandbox. No layer here is a universal isolation boundary. ## Execution status Local inference is an **experimental preview**. Selected embedded Kaze paths have recorded real model-and-authorized-MCP journeys on local debug builds, including one using existing local weights. That evidence does not establish every provider, released artifact or application. Verify each example's backend and execution path before claiming an end-to-end result. ## Next steps --- # Server & inference URL: https://docs.sofuu.xyz/server/ Sofuu binds HTTP sockets in the same process that runs your script, so a server can call `sofuu.ai` and `sofuu.memory` without an IPC hop. Two surfaces exist: a JavaScript server built on `sofuu.http.createServer`, and the OpenAI-compatible server started with `sofuu serve`. ## Create a server `sofuu.http.createServer(cb)` binds a non-blocking server over OS sockets and calls `cb` with `req` and `res` for every request. The example below streams model output as Server-Sent Events. ```js // app.js — a server that streams model tokens over Server-Sent Events const server = sofuu.http.createServer(async (req, res) => { if (req.url === "/chat") { const stream = sofuu.ai.stream("Explain quantum mechanics simply.", { provider: "openai", model: "gpt-4o", }); res.writeHead(200, { "Content-Type": "text/event-stream" }); for await (const chunk of stream) res.write(chunk.text); res.end(); } else { res.writeHead(200); res.end("AI Edge Runtime Active"); } }); server.listen(8080, "0.0.0.0"); console.log("Server bound on port 8080."); ``` The handler sees `req.url` and `req.method`; the body is buffered before the handler runs. A response offers `writeHead(status, headers)`, `write(chunk)`, and `end(data)`. `server.listen(port, host)` refs the handle and keeps the process alive while listening, matching Node semantics: a script that ends with a bound server keeps serving. `server.unref()` releases the loop while leaving the socket bound, and `server.ref()` reverses it. An embedded host (`sofuu_rt_new`) uses the opposite default and calls `ref()` per server it wants held open. ## Request and response surface | Call | Behavior | | --- | --- | | `sofuu.http.createServer(cb)` | Creates the server and registers the request handler. | | `server.listen(port, host)` | Binds and refs the listening handle. | | `server.unref()` / `server.ref()` | Stops or resumes holding the event loop open. Returns the server. | | `res.writeHead(status, headers)` | Sends the status line and headers. | | `res.write(chunk)` | Writes body bytes without ending the response. | | `res.end(data)` | Flushes the body and finishes the response. | | `sofuu.fetch(url, opts?)` | HTTP(S) client over a statically linked curl, resolving to a response with `.text()` and `.json()`. Also reachable as `sofuu.http.fetch`. | In an embedded host, the `http.serve` funnel takes `{handler, port, host}`, where `handler` names a global function. ## The OpenAI-compatible server `sofuu serve` runs the shipped handler and exposes an OpenAI-shaped API over a local model, a brain, or both. It needs no external daemon, but it does need a model file or brain. ```bash sofuu serve --model ~/models/qwen.gguf --model-id qwen --port 7707 sofuu serve --brain ./brain.qtsq ``` | Route | Notes | | --- | --- | | `GET /healthz`, `GET /livez` | No auth, no data. Liveness only. | | `GET /health` | Obeys the token when one is configured. | | `GET /v1/models` | Configured model ids from `--model-id`, defaulting to the file's basename. | | `POST /v1/chat/completions` | Chat with stream or JSON, usage, `finish_reason`, `stop`, and `tools`. | | `POST /v1/completions`, `POST /infer` | Raw-text completion; the prompt is not chat-templated. | | `POST /v1/embeddings` | Local embedder; batch cap 64 inputs, 8192 tokens each. | | `POST /v1/agent/runs` | Runs `sofuu.agent.run` with SSE step events, or JSON with `stream: false`. | | `GET /v1/tools`, `POST /v1/tools/:name/call` | Tool inventory and execution, with policy verdicts. | | `POST /remember`, `GET /recall`, `POST /forget` | Brain routes; `503 brain_unavailable` when no brain is configured. | Every route except `/healthz` and `/livez` requires `Authorization: Bearer `. The token comes from `--token` or `SOFUU_SERVE_TOKEN`, otherwise one is generated into `~/.sofuu/serve_token` with mode `0600`. A bind to a host other than `127.0.0.1` or `localhost` refuses to start with a generated token, so pass one explicitly. `policy.http.auth = "none"` is the only way to disable auth, and it prints a warning at start. Routes, auth rules, and the compatibility matrix are in `docs/HTTP-SERVER.md`. ## Compiled micro-server The compiled form packages an MCP server against the micro runtime base: `sofuu mcp build server.ts -o dist/my-mcp-server`, or the equivalent `sofuu compile server.ts --profile micro -o dist/my-mcp-server`. The result is a single file; OS libraries and any services the server calls are still required. See [MCP](/mcp/) for the server API and transport options. ## Local inference (preview) The built-in GGUF and SafeTensors engine is an experimental preview, decoupled from the production launch gate. Support depends on the model file and on the OS libraries present on the machine. For deployed workloads, use llama.cpp or another backend through the `llamacpp` provider plugin, or a remote endpoint. The engine loads models in-process with zero-copy `mmap` and executes on Apple Metal, ARM NEON, or x86_64 AVX2, with no Python and no separate model server. ```bash sofuu infer ./model.gguf "Hello" sofuu serve --infer -m ./model.gguf ``` A successful load says nothing about output quality, context length, or throughput. Measure the workload you intend to ship, and keep a fallback provider. ## Edge swarms (preview) Swarm layer pipelining across machines is a preview. Treat the commands below as an interface sketch, not a supported deployment topology. ```bash sofuu swarm worker --model ./model.gguf --listen 0.0.0.0:9001 --layers 16..32 sofuu swarm leader --model ./model.gguf --workers 192.168.1.50:9001 "Hello" ``` A worker holds a layer range and listens on a socket; the leader addresses one or more workers. Nothing here changes the auth story of `sofuu serve`, so do not expose a worker to an untrusted network. ## Next The [API reference](/api/) lists the `sofuu.http`, `sofuu.ai`, and `sofuu.fetch` shapes. [Troubleshooting](/troubleshooting/) covers provider configuration, model-file failures, and MCP transport errors. --- # Embed URL: https://docs.sofuu.xyz/embed/ `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. Sofuu is **0.3.0-beta**, and the embedding surface may change additively. Call `sofuu_embed_abi_version()` at startup and test on the platform and toolchain you ship. Published desktop host builds are macOS-only for now; verify iOS and Android package availability for your release. ## Build and link ```bash 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 ```c #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. ```c 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 ```c 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: ```json { "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. ```swift 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. ## Next steps --- # Kaze URL: https://docs.sofuu.xyz/kaze/ Kaze is intended to be general-purpose within AI, spanning software and AI-powered physical systems, not all computing. Today's embedded engine supports a narrower set of bounded, indentation-sensitive routines. Capabilities require declarations, grants, policy and an available backend. The planned direction is one language with human-oriented and machine-oriented source syntaxes sharing semantics and authorization. Machine syntax, conversion and parity are not implemented; the grammar remains open. Sofuu embeds a Kaze engine that reports **0.1**. Standalone Kaze is **1.0** (`kaze --version`), and its bytecode format is **4**. The embedded engine writes format **2** and reads legacy format **1**. Features and bytecode are not interchangeable in either direction: a program checked against the [1.0 reference](/kaze/reference/) is not automatically a program the embedded host will run. ## What the language covers A program is an optional `needs:` line followed by at least one `action`, `check`, `filter`, `when`, or `every` item. Blocks open after a colon and continue on indented lines; tabs outside strings and comments are rejected, and `#` starts a comment. Values are numbers, text, booleans, lists, host-supplied records, points, and `nothing`. There is no map literal, no field assignment, no `break` or `continue`, and no direct routine-to-routine call — `use "file.kaze"` is an include resolved at compile time. The embedded engine defaults to 200,000 fuel units, a 256 KiB string arena, a 4 MiB collection heap, a 256-value operand stack, and 255 compiler slots per item. The standalone 1.0 reference documents its own numbers for the same budgets, so read the limits from the engine you are actually running. ## Declaring capabilities Capability families are named in the header. A declaration enables the operation names at check time; it does not grant them at run time. ```kaze needs: policy filter limit_length(text): if length of text > 120: reject with "too long" otherwise: allow text ``` Every capability call needs three things: the family in `needs:`, an explicit host grant (`--cap`), and a policy that permits the operation. A missing backend is refused rather than simulated — `--no-policy` leaves capability calls denied, and only an explicitly selected `--cap drone=sim` or `--cap rover=sim` supplies test state, which the run report labels as simulated. ## Routines, entrypoints, and schedules `action` and `check` routines execute a body and may return a value; falling through returns `nothing`. A `filter` must terminate on every path with `allow`, `reject`, or `return`, though a plain `return` can end it without a verdict. Without `--entry`, the runner prefers a root `main`, then the sole root routine, and refuses an ambiguous multi-routine file with `E_KAZE_ENTRY`. `when` and `every` items are hooks, not entrypoints. They run on supervisor ticks, which are opt-in: ticks default to `0`, virtual time starts at zero, and virtual time advances without sleeping unless `--pace` is passed. An entry and its hooks share one run's VM and fuel budget. ```kaze needs: drone action recover(): try: arm drone otherwise with problem: return problem.code when link lost for 3 seconds: return to launch ``` The front end checks that example without executing it. Running the hook needs a drone grant, a policy, and a configured backend. ```kaze action main(amount): let total = 0 for each value in [1, 2, 3]: set total to total + value return total + amount ``` `sofuu script run example.kaze --arg amount=4 --json` reports the rendered result `10`. ## Commands | Command | Purpose | | --- | --- | | `sofuu script run agent.kaze` | Parses, checks, compiles, and executes a routine. Accepts `--entry`, `--arg name=value`, `--cap`, `--policy`, `--fuel`, `--ticks`, and `--sim`. | | `sofuu script check agent.kaze` | Parses and checks without executing. `--json` reports item, capability, and constant counts. | | `sofuu script compile agent.kaze -o agent.kazebc` | Emits embedded-engine bytecode. Without `-o` the command prints the size and writes no file. | | `sofuu script repl` | Interactive session over the same engine, with `.needs`, `.cap`, `.run`, and `.clear`. | | `sofuu compile agent.kaze -o agent` | Packages a supported routine as a standalone executable. | ## Configuration for compiled agents A Sofuu-compiled agent resolves a routine parameter in this order: `--arg name=value` or a positional value, then `AGENT_` or `SOFUU_*`, then `--config ` or `./agent.config.json`. Missing parameters are reported as `E_KAZE_PARAM` on the current source. The standalone `kaze` CLI has different configuration support: it has no `--config` option, and it does not bind `AGENT_*` or `SOFUU_*` to routine parameters. Use `--arg` there. ## Status Selected embedded paths have recorded real model-and-authorized-MCP journeys on local debug builds, using a remote provider and separately existing local GGUF weights. Unavailable backends fail; physical drone/rover simulation must be explicitly selected and labelled. This does not verify published artifacts, other providers, the separate standalone engine or physical hardware. --- # Kaze 1.0 reference URL: https://docs.sofuu.xyz/kaze/reference/ Kaze's intended scope is AI software and AI-powered physical systems, not all computing. One language with human-oriented and machine-oriented source syntaxes is planned; machine syntax and conversion are not implemented in this snapshot. **Snapshot:** 2026-11-10. This inventory describes the current standalone `kaze/` source and its CLI after the capability-safety changes. It does not establish the contents of a published release, the behavior of a different checkout, or successful operation on physical hardware. Standalone **Kaze is 1.0** (`kaze --version`); the Rust package is `1.0.0` and its bytecode format is **4**. Sofuu also has a separate embedded Kaze engine that reports **0.1**; its current source writes format **2** and reads legacy format **1**. Their features and bytecode are not interchangeable. This document is for standalone Kaze 1.0. The embedded engine has a separate `docs/specs/KAZE-CURRENT-SURFACE.md` inventory in the Sofuu workspace. ## Tag key Every inventory row has at least one status tag. Tags describe this snapshot; `IMPLEMENTED` alone is a source-code observation, not proof of deployment. | Tag | Meaning | | --- | --- | | `[IMPLEMENTED]` | Present in the inspected standalone source for the stated scope. | | `[VERIFIED]` | Additionally checked locally; the evidence section identifies pure checks, real local operations, or explicitly labelled robotics simulation. | | `[PARTIAL]` | Present with a stated gap, restriction, or incomplete enforcement. | | `[LIVE-PATH]` | A real hardware code path exists; a configured device and appropriate permissions are still required. | | `[UNVERIFIED]` | This inventory did not verify the stated physical device, external integration, or published artifact. | | `[SIMULATED]` | The built-in path supplies simulated state or an imitation rather than a real external operation. | | `[REGISTRY-ONLY]` | The name and arity are recognized, but the inspected built-in host has no matching implementation. | | `[POST-BASELINE]` | This detail differs from the frozen standalone v1.0 baseline; the release compatibility decision remains open. | | `[UNSUPPORTED]` | No corresponding general feature is implemented in this standalone surface. | | `[TARGET]` | A repository requirement or intended behavior, not a verified implementation. | **Policy note:** `RULES.md` §1.9 permits explicitly selected and labelled robotics/drone simulation for testing. In this source snapshot the standalone host refuses unavailable non-robotics backends instead of simulating them. Simulator selection is explicit and reported; physical hardware has not been verified. ## 1. Syntax ### 1.1 Source structure and lexical rules | Item | Tag | Exact form and behavior | | --- | --- | --- | | File encoding | `[IMPLEMENTED]` | UTF-8 source. `kaze run -` and `kaze check -` read source from stdin. | | Program | `[IMPLEMENTED]` | Optional headers followed by at least one `action`, `check`, `filter`, `when`, or `every` item. A header-only file is rejected. | | Header order | `[IMPLEMENTED]` | `needs:` and `use` lines can appear in either order before the first item. Each file permits at most one `needs:` line. | | Block | `[IMPLEMENTED]` `[VERIFIED]` | A colon ends the header; the body starts on the next line with at least one indented statement. Dedents must match a previous indentation level. | | Indentation | `[IMPLEMENTED]` | Spaces are used; the formatter uses four spaces per level. Tabs in code outside strings/comments are rejected. | | Comments | `[IMPLEMENTED]` | `#` outside a string starts a comment through the end of the line. | | Continuation | `[IMPLEMENTED]` | Newlines inside `(...)` or `[...]` continue the expression. | | Identifier | `[IMPLEMENTED]` | ASCII `[A-Za-z_][A-Za-z0-9_]*`; names are case-sensitive. | | Text literal | `[IMPLEMENTED]` | Double-quoted, single-line text. Supported escapes: `\n`, `\t`, `\"`, `\\`. | | Number literal | `[IMPLEMENTED]` | Decimal integer or fraction such as `12` or `1.25`; the literal must fit a finite `f64`. Leading `-` is an operator. Exponents and hexadecimal are not numeric literals. | | Punctuation | `[IMPLEMENTED]` | `:`, `(`, `)`, `,`, `.`, `%`, `+`, `-`, `*`, `/`, `<`, `>`, `=`, `[`, `]`; plus `<=`, `>=`, `==`, `!=`. | | Semicolon and braces | `[UNSUPPORTED]` | No general semicolon statement separator, `{...}` block, or map literal syntax. | ### 1.2 Header and declaration syntax | Syntax | Tag | Meaning and constraints | | --- | --- | --- | | `needs: family, family` | `[IMPLEMENTED]` | Declare capability resources. Duplicate names in one header are rejected. A declaration is not itself a backend grant. | | `use "path.kaze"` | `[IMPLEMENTED]` `[VERIFIED]` | Compile-time include. The path must end in `.kaze`; relative paths resolve from the importing file. | | `action name(a, b):` | `[IMPLEMENTED]` | Declare an executable named routine with positional signature names. | | `check name(a, b):` | `[IMPLEMENTED]` | Declare a named check routine. Runtime entry binding works like an action. | | `filter name(a, b):` | `[PARTIAL]` `[VERIFIED]` | Declare a policy-oriented routine; the checker allows a plain `return`, which can yield no verdict. | | `when condition:` | `[IMPLEMENTED]` | Declare a hook evaluated on each requested supervisor tick. | | `every 100 ms:` | `[IMPLEMENTED]` | Declare a periodic hook with a numeric literal and time unit. It runs on ticks whose virtual time is divisible by its period. A zero period is never due. | | Duplicate routine names | `[IMPLEMENTED]` | Rejected within one file and on module merge. Hook names are generated. | | Parameter defaults / annotations | `[UNSUPPORTED]` | Routine signatures contain names only; no default values or source type annotations. | ### 1.3 Statements | Syntax | Tag | Meaning | | --- | --- | --- | | `let name = expression` | `[IMPLEMENTED]` `[VERIFIED]` | Bind a value in the current scope. | | `set name = expression` | `[IMPLEMENTED]` | Reassign an existing binding. | | `set name to expression` | `[IMPLEMENTED]` `[VERIFIED]` | Alternative spelling for `set`. | | `if condition:` | `[IMPLEMENTED]` | Run its indented block when the condition is true. | | `otherwise:` after `if` | `[IMPLEMENTED]` | Optional alternative block. | | `for each item in values:` | `[IMPLEMENTED]` `[VERIFIED]` | Iterate over a list; the loop variable is local to its body. | | `while condition:` | `[IMPLEMENTED]` | Repeat while the condition is true, subject to the run's fuel and applicable deadline. | | `try:` | `[IMPLEMENTED]` | Start a protected block for the specific recoverable host errors in §5. | | `otherwise:` after `try` | `[IMPLEMENTED]` | Required recovery block; it can omit an error binding. | | `otherwise with error:` | `[IMPLEMENTED]` | Recovery block with `error.code`, `error.message`, and `error.line`. | | `return` | `[IMPLEMENTED]` | End the current item with the runtime value `nothing`. | | `return expression` | `[IMPLEMENTED]` `[VERIFIED]` | End the current item with that value. | | `return to launch` | `[IMPLEMENTED]` | Capability sentence for `drone.rtl()`; this is a host operation, not the ordinary `return` statement. | | Expression statement | `[IMPLEMENTED]` | Evaluate an expression and discard its value unless it is a policy verdict. | | `break` / `continue` | `[UNSUPPORTED]` | No general loop-control statements. | | Field or index assignment | `[UNSUPPORTED]` | `set record.field ...` and `set list[index] ...` are not general assignment forms. | ### 1.4 Expressions and operators | Form | Tag | Meaning and restrictions | | --- | --- | --- | | `name` | `[IMPLEMENTED]` | Read a parameter or local binding; some unbound names can resolve as bare telemetry. | | `(expression)` | `[IMPLEMENTED]` | Group an expression. | | `[a, b, ...]` | `[IMPLEMENTED]` | Ordered list literal; at most 255 elements per literal. | | `value[index]` | `[IMPLEMENTED]` | Zero-based read from a list, text, or point; index must be a nonnegative integer in range. | | `name.field` | `[IMPLEMENTED]` | Read a field from a named record or point. A missing record field returns `nothing`. | | `receiver.operation(args)` | `[PARTIAL]` | Call a registered capability operation. The receiver is a resource/family name, not a general object method. At the beginning of a statement, `log.info(...)` is parsed as the `log` sentence and fails; use `log value` or place the call in an expression. | | `log.info(...)` as a statement | `[PARTIAL]` `[VERIFIED]` | Rejected by the current parser because `log` starts a sentence. `return log.info(...)` passes the front end; `log value` is the usual sentence form. Other `log.(...)` statements encounter the same dispatch. | | `length of value` | `[IMPLEMENTED]` | Character count for text, element count for lists, and Euclidean magnitude for a point. | | `-value` | `[IMPLEMENTED]` | Numeric negation; point negation is supported. | | `not value` | `[IMPLEMENTED]` | Boolean negation; the checker expects boolean where it knows the type. | | `a + b` | `[IMPLEMENTED]` | Add numbers or points, or concatenate two text values. | | `a - b` | `[IMPLEMENTED]` | Subtract numbers or points. | | `a * b` | `[IMPLEMENTED]` | Multiply numbers or scale a point by a number. | | `a / b` | `[IMPLEMENTED]` | Divide numbers or divide a point by a number; zero divisor raises `E_KAZE_DIV0`. | | `a % b` | `[PARTIAL]` `[VERIFIED]` | Numeric remainder. Immediately after a numeric literal `%` can instead be consumed as a percent unit: `return 5 % 2` returned `5` in a local probe. Use `return (5) % 2` or a variable for the left operand. | | `a < b`, `a <= b` | `[IMPLEMENTED]` | Ordering comparisons for compatible numbers or text. | | `a > b`, `a >= b` | `[IMPLEMENTED]` | Ordering comparisons for compatible numbers or text. | | `a == b`, `a != b` | `[IMPLEMENTED]` | Equality / inequality. Points compare components; lists and records compare their heap identities, not deep structural contents. | | `a and b` | `[IMPLEMENTED]` | Short-circuit conjunction; the right side is skipped if the left is false. | | `a or b` | `[IMPLEMENTED]` | Short-circuit disjunction; the right side is skipped if the left is true. | | `routine(args)` | `[UNSUPPORTED]` | No direct call from one user-defined Kaze routine to another. Use `--entry` to select a routine. | | Chained comparisons | `[UNSUPPORTED]` | The grammar handles one comparison at a time; do not rely on `a < b < c`. | | String interpolation | `[UNSUPPORTED]` | Build supported text using literals and `+` between text values. | Operator precedence, from tighter to looser: postfix/indexing and angle conversion; unary `-`; `*` `/` `%`; `+` `-`; comparison; `not`; `and`; `or`. Use parentheses when the intended grouping is not obvious. ### 1.5 Mathematical and spatial forms | Syntax | Tag | Result and constraints | | --- | --- | --- | | `vector(x, y)` | `[IMPLEMENTED]` | Create a point with `z = 0`. | | `vector(x, y, z)` | `[IMPLEMENTED]` `[VERIFIED]` | Create a point from three numeric components. | | `distance between a and b` | `[IMPLEMENTED]` | Great-circle ground distance in meters; `a` and `b` are geographic points. | | `slant distance between a and b` | `[IMPLEMENTED]` | Ground distance combined with altitude difference. | | `bearing of offset` | `[IMPLEMENTED]` | Compass bearing of a local vector in degrees: north 0, east 90. | | `bearing from a to b` | `[IMPLEMENTED]` | Initial compass bearing between two geographic points. | | `bearing to target` | `[PARTIAL]` | Uses ambient latitude/longitude from exactly one declared hardware resource in the file; backend availability controls whether the position is real. | | `sin(x)` | `[IMPLEMENTED]` | Sine of a number in radians. | | `cos(x)` | `[IMPLEMENTED]` | Cosine of a number in radians. | | `atan2(y, x)` | `[IMPLEMENTED]` | Two-argument arctangent; result is radians. | | `sqrt(x)` | `[IMPLEMENTED]` `[VERIFIED]` | Square root; a negative input raises `E_KAZE_MATH`. | | `x in radians` | `[IMPLEMENTED]` | Convert degrees to radians. | | `x in degrees` | `[IMPLEMENTED]` | Convert radians to degrees. | | `link lost for 3 seconds` | `[PARTIAL]` | Boolean link-silence expression; requires a drone declaration, grant, valid policy, and configured backend. Window must be 1 through 4,294,967,295 ms. A real result requires a live link. | | `policy detects kind in text` | `[PARTIAL]` | Lowers to `policy.detects(kind, text)`; detector behavior depends on the host. | | `recall memories matching query` | `[REGISTRY-ONLY]` | Lowers to `memory.recall(query)`; the standalone built-in host currently refuses it with `E_CAP_MISSING`. | ### 1.6 Sentence-form capability calls These forms are syntactic sugar. Their tags describe parsing; §4 gives the separate real-backend status and required declaration/grant. | Sentence | Tag | Lowers to | | --- | --- | --- | | `log value` | `[IMPLEMENTED]` | `log.info(value)`. | | `log info value` | `[IMPLEMENTED]` | `log.info(value)`. | | `log warn value` / `log warning value` | `[IMPLEMENTED]` | `log.warn(value)`. | | `log error value` | `[IMPLEMENTED]` | `log.error(value)`. | | `log debug value` | `[IMPLEMENTED]` | `log.debug(value)`. | | `send alert value` | `[IMPLEMENTED]` | `alert.send(value)`. | | `remember value as label` | `[IMPLEMENTED]` | `memory.save(label, value)`. | | `recall memories matching query` | `[IMPLEMENTED]` | `memory.recall(query)`. | | `allow` / `allow value` | `[IMPLEMENTED]` | `policy.allow()` / `policy.allow(value)` and terminate the item. | | `reject with reason` | `[IMPLEMENTED]` | `policy.reject(reason)` and terminate the item. | | `arm drone` | `[IMPLEMENTED]` | `drone.arm()`; the noun resolves to its family. | | `takeoff to height` | `[IMPLEMENTED]` | `drone.takeoff(height)`. | | `fly to point` | `[IMPLEMENTED]` | `drone.goto(point)`. | | `fly to point at altitude` | `[IMPLEMENTED]` | `drone.goto(point, altitude)`. | | `land` / `land drone` | `[IMPLEMENTED]` | `drone.land()`. | | `hold` / `hold position` | `[IMPLEMENTED]` | `drone.hold()`. | | `return to launch` | `[IMPLEMENTED]` | `drone.rtl()`. | | `stop drone` / `stop rover` | `[IMPLEMENTED]` | `.stop()`. | | `drive` / `drive forward` | `[IMPLEMENTED]` | `rover.forward()`; `at speed` supplies a speed. | | `drive backward` | `[IMPLEMENTED]` | `rover.backward()`; `at speed` supplies a speed. | | `turn left by degrees` | `[IMPLEMENTED]` | `rover.turn_left(degrees)`. | | `turn right by degrees` | `[IMPLEMENTED]` | `rover.turn_right(degrees)`. | | `turn on name` | `[IMPLEMENTED]` | `device.set_relay("name", true)`. | | `turn off name` | `[IMPLEMENTED]` | `device.set_relay("name", false)`. | | `pulse name for duration` | `[IMPLEMENTED]` | `device.pulse("name", duration)`. | ## 2. Values and units ### 2.1 Runtime values | Value | Tag | Creation, access, and behavior | | --- | --- | --- | | Number | `[IMPLEMENTED]` | Finite `f64`; for example `12`, `3.5`, or a numeric `--arg`. Arithmetic can raise overflow or division errors. | | Text | `[IMPLEMENTED]` | UTF-8, for example `"hello"`; text concatenation uses `+`. Indexing and length use Unicode scalar values, not bytes or grapheme clusters. | | Boolean | `[IMPLEMENTED]` | Source literals `true` and `false`. | | List | `[IMPLEMENTED]` | `[1, "a", true]` or a JSON array argument; ordered, zero-based, and heap-backed. | | Record/map | `[PARTIAL]` | A JSON object argument or host can supply a record. Read `name.field`; no record literal or field assignment. | | Point/vector | `[IMPLEMENTED]` | `vector(x, y)` or `vector(x, y, z)`. Read indexes `0`, `1`, `2` or named components below. | | Nothing/unit | `[IMPLEMENTED]` | Runtime value from an empty return, a missing field, JSON `null`, or a missing parameter. No general `nothing` source literal. | | Error record | `[IMPLEMENTED]` | In a recovery block, `.code` and `.message` are text and `.line` is a number. | | Point component | Tag | Equivalent names | | --- | --- | --- | | First component | `[IMPLEMENTED]` | `.x`, `.lat`, `.latitude`, or `[0]`. | | Second component | `[IMPLEMENTED]` | `.y`, `.lon`, `.longitude`, or `[1]`. | | Third component | `[IMPLEMENTED]` | `.z`, `.alt`, `.altitude`, or `[2]`. | | Geographic place | `[IMPLEMENTED]` | Spatial distance/bearing checks latitude `-90..90` and longitude `-180..180`; invalid places raise `E_KAZE_RANGE`. | ### 2.2 Numeric literal units | Unit | Tag | Accepted suffixes | Representation | | --- | --- | --- | --- | | Distance | `[IMPLEMENTED]` | `m`, `meter`, `meters` | Numeric value in meters. | | Speed | `[IMPLEMENTED]` | `m/s` | Numeric value in meters per second. | | Angle | `[IMPLEMENTED]` | `deg`, `degree`, `degrees` | Numeric value in degrees. | | Time | `[IMPLEMENTED]` | `s`, `sec`, `second`, `seconds` | Numeric value in seconds. | | Milliseconds | `[IMPLEMENTED]` | `ms`, `millisecond`, `milliseconds` | Normalized to seconds: `500 ms` becomes `0.5`. | | Percentage | `[IMPLEMENTED]` | `%`, `percent` | Whole-number convention: `20%` is `20`, not `0.2`. | | Dimensional mismatch checking | `[PARTIAL]` `[VERIFIED]` | Any unit combination | The current checker accepts `1 meters < 1 seconds`; units are not retained as runtime tags. Do not assume dimensional safety. | | Arbitrary/user-defined units | `[UNSUPPORTED]` | — | No general unit declaration or conversion system. | ## 3. Routines, entries, and scheduling | Item | Tag | Behavior | | --- | --- | --- | | Action | `[IMPLEMENTED]` | A named `action` may return a value or `nothing`. | | Check | `[IMPLEMENTED]` | A named `check` is selected and bound like an action; it has no separate mandatory boolean-return rule. | | Filter | `[PARTIAL]` `[VERIFIED]` | Intended to stop at `allow` or `reject`. A plain `return` also passes the current checker and can yield a null verdict. | | Explicit entry | `[IMPLEMENTED]` `[VERIFIED]` | `--entry name` selects a named item, including an imported item. Missing names give `E_KAZE_ENTRY`. | | Root `main` | `[IMPLEMENTED]` | Without `--entry`, a `main` from the root file is preferred. | | Single root routine | `[IMPLEMENTED]` | Without root `main`, the sole root action/check/filter is selected. | | Multiple root routines | `[IMPLEMENTED]` | Without an explicit entry or root `main`, ambiguous selection raises `E_KAZE_ENTRY`. | | Hooks-only root | `[IMPLEMENTED]` | Can run with no entry; hooks require ticks to execute. | | Imported implicit entry | `[UNSUPPORTED]` | Imported routines do not become the implicit root entry. | | Parameters | `[PARTIAL]` | Bound by name or numeric key in `--arg`. Missing values become `nothing` instead of an early missing-parameter diagnostic. | | `when` hook | `[IMPLEMENTED]` | Predicate runs for each requested tick; body runs when true. | | `every` hook | `[IMPLEMENTED]` | Runs when period divides virtual tick time. Time begins at `0`, so a positive period is initially due. | | Tick pacing | `[IMPLEMENTED]` | `--pace` sleeps between ticks; without it scheduling advances virtual time without a sleep. | | Hook state | `[PARTIAL]` | VM locals/stack are recreated for each item; arena and heap are cleared after each tick. Host state can remain separate. | | Routine calls | `[UNSUPPORTED]` | A routine cannot directly invoke another routine using ordinary call syntax. | | Runtime imports / namespaces | `[UNSUPPORTED]` | `use` is an include at compilation, with a shared global item namespace. | | Import cycle / collision | `[IMPLEMENTED]` | Cycles and duplicate item names fail. Shared dependencies are included once. | ### Example: pure action ```kaze action main(amount): let total = 0 for each value in [1, 2, 3]: set total to total + value return total + amount ``` `kaze run example.kaze --arg amount=4 --plain` returns `10`. ### Example: filter and error recovery ```kaze needs: policy filter limit_length(text): if length of text > 120: reject with "too long" otherwise: allow text ``` ```kaze needs: drone action recover(): try: arm drone otherwise with problem: return problem.code when link lost for 3 seconds: return to launch ``` The examples were checked without executing their capabilities. Actual drone operations need an authorized, configured backend. ## 4. Capabilities ### 4.1 Gate and backend tags Every operation below requires a matching `needs:` declaration, an explicit host grant, and a valid policy. Selected physical arguments are checked before dispatch. An operation's tag describes the built-in standalone host, not every possible custom `CapHost` supplied by an embedding application. | Gate | Tag | Current behavior | | --- | --- | --- | | H-1: declaration | `[IMPLEMENTED]` | An undeclared family is rejected; the checker can reject it before execution. | | H-2: grant | `[IMPLEMENTED]` `[POST-BASELINE]` `[VERIFIED]` | Requires an explicit host grant for every capability family. | | H-3: policy | `[IMPLEMENTED]` `[POST-BASELINE]` `[VERIFIED]` | Missing, malformed, unsupported, or denying policy causes `E_CAP_DENIED`. `--no-policy` does not bypass this gate. | | H-4: arguments | `[PARTIAL]` | Selected physical arguments have type/range checks and are rejected rather than clamped; coverage is not universal. | | Default host | `[IMPLEMENTED]` `[POST-BASELINE]` | No physical or simulated backend is selected implicitly. Missing backends return `E_CAP_MISSING`. | | Simulator selection | `[IMPLEMENTED]` `[POST-BASELINE]` `[VERIFIED]` | `drone=sim` and `rover=sim` must be selected explicitly for testing; run reports identify selected simulators. | | Live host fallback | `[IMPLEMENTED]` `[POST-BASELINE]` `[VERIFIED]` | Unconfigured sensor, device, alert, memory, AI, and tool operations return unavailable errors rather than simulated success. | | Link-loss gate | `[IMPLEMENTED]` `[POST-BASELINE]` `[VERIFIED]` | Link monitoring checks the drone declaration, grant, policy, and backend before reading the host. | | Lazy live link | `[IMPLEMENTED]` `[POST-BASELINE]` `[VERIFIED]` | The live drone connection opens only after the relevant VM gate approves the operation. | | Live telemetry freshness | `[PARTIAL]` `[TARGET]` | The live link uses a two-second timeout on received bytes, not a 1.5-second heartbeat and per-field telemetry freshness veto. Partial targets can use a previously reported value whose age is unknown. The `RULES.md` safety requirement is not yet met. | | Live drone actuation | `[POST-BASELINE]` `[VERIFIED]` `[UNSUPPORTED]` | The built-in host returns `E_CAP_DENIED` for live actuation before opening the link until the required freshness checks are implemented. Explicit drone simulation remains available for testing. | | Physical hardware execution | `[UNVERIFIED]` | The source has MAVLink and Linux GPIO/PWM paths; this inventory did not run a vehicle or device. | ### 4.2 Drone operations These require `needs: drone`, a `drone` grant and a valid policy. MAVLink actuation code exists but is disabled by the built-in host until freshness checks are implemented. The explicitly selected simulator is for testing only; the live path was not physically verified here. | Operation | Tag | Arguments and behavior | | --- | --- | --- | | `drone.arm()` | `[LIVE-PATH]` `[UNVERIFIED]` | No arguments; request arming and wait for armed telemetry on the live path. | | `drone.takeoff(height)` | `[LIVE-PATH]` `[UNVERIFIED]` | One number in meters; gate checks `0..500`. | | `drone.goto(target)` | `[LIVE-PATH]` `[UNVERIFIED]` `[PARTIAL]` | One point or numeric latitude. The currently disabled partial live-target code requires previously reported telemetry rather than fabricated coordinates or altitude; freshness is not checked. | | `drone.goto(target, altitude)` | `[LIVE-PATH]` `[UNVERIFIED]` | Two arguments; supported point/altitude or numeric forms have backend-specific interpretation. | | `drone.goto(lat, lon, altitude)` | `[LIVE-PATH]` `[UNVERIFIED]` | Three numeric arguments; latitude is checked `-90..90`, longitude `-180..180`, and altitude `0..500` meters. | | `drone.land()` | `[LIVE-PATH]` `[UNVERIFIED]` | No arguments; request landing. | | `drone.rtl()` | `[LIVE-PATH]` `[UNVERIFIED]` | No arguments; request return to launch. | | `drone.hold()` | `[LIVE-PATH]` `[UNVERIFIED]` | No arguments; request hold/loiter. | | `drone.stop()` | `[LIVE-PATH]` `[UNVERIFIED]` | No arguments; live path maps to hold/loiter. | | `drone.telemetry(field)` | `[LIVE-PATH]` `[UNVERIFIED]` | One field name; live telemetry can report a link error if no reading arrives. | ### 4.3 Rover and sensor operations These require a family declaration and grant. Rover simulation requires an explicit testing selection; no built-in live rover or sensor backend has been established. Sensor calls now fail rather than return simulated readings. | Operation | Tag | Arguments and behavior | | --- | --- | --- | | `rover.forward()` | `[SIMULATED]` | No speed argument; simulator uses its own default. | | `rover.forward(speed)` | `[SIMULATED]` | One speed; supplied value is checked `0..10` m/s. | | `rover.backward()` | `[SIMULATED]` | No speed argument; simulator uses its own default. | | `rover.backward(speed)` | `[SIMULATED]` | One speed; supplied value is checked `0..10` m/s. | | `rover.turn_left(angle)` | `[SIMULATED]` | One angle in degrees. | | `rover.turn_right(angle)` | `[SIMULATED]` | One angle in degrees. | | `rover.stop()` | `[SIMULATED]` | No arguments. | | `rover.telemetry(field)` | `[SIMULATED]` | One field name. | | `sensor.temperature()` | `[REGISTRY-ONLY]` | No arguments; built-in host returns `E_CAP_MISSING`. | | `sensor.humidity()` | `[REGISTRY-ONLY]` | No arguments; built-in host returns `E_CAP_MISSING`. | | `sensor.distance()` | `[REGISTRY-ONLY]` | No arguments; built-in host returns `E_CAP_MISSING`. | | `sensor.front_distance()` | `[REGISTRY-ONLY]` | No arguments; built-in host returns `E_CAP_MISSING`. | | `sensor.read(name)` | `[REGISTRY-ONLY]` | One name or pin; built-in host returns `E_CAP_MISSING`. | | `sensor.telemetry(field)` | `[REGISTRY-ONLY]` | One field name; built-in host returns `E_CAP_MISSING`. | ### 4.4 Device operations These require `needs: device` or a device alias and a `device` grant. | Operation | Tag | Arguments and behavior | | --- | --- | --- | | `device.set_relay(name, on)` | `[LIVE-PATH]` `[UNVERIFIED]` | Name and boolean or finite numeric state; live Linux GPIO requires a named pin. | | `device.pulse(name, seconds)` | `[LIVE-PATH]` `[UNVERIFIED]` | Name and duration; gate checks `0..60` seconds. | | `device.read_gpio(name)` | `[LIVE-PATH]` `[PARTIAL]` `[UNVERIFIED]` | One name; live path returns a boolean, while the checker currently infers a number. The mismatch can reject an `if` condition. | | `device.set_duty(name, percent)` | `[LIVE-PATH]` `[UNVERIFIED]` | Name and PWM percentage; gate checks `0..100`. A named PWM channel is required for the live PWM path. | | Missing device mapping | `[IMPLEMENTED]` `[POST-BASELINE]` | Without a suitable live GPIO/PWM mapping, device operations return `E_CAP_MISSING`. | ### 4.5 Memory, policy, logging, alerts, AI, and tools | Operation | Tag | Arguments and current behavior | | --- | --- | --- | | `memory.save(label, value)` | `[REGISTRY-ONLY]` | Two arguments; the standalone built-in host returns `E_CAP_MISSING`. | | `memory.recall(query)` | `[REGISTRY-ONLY]` | One argument; the standalone built-in host returns `E_CAP_MISSING`. | | `policy.detects(kind, text)` | `[PARTIAL]` | Two arguments; the built-in host uses a small local pattern detector for `secrets` and `prompt_injection`; unknown kinds return `E_CAP_MISSING`. | | `policy.detect(kind, text)` | `[PARTIAL]` | Alias operation with the same built-in detection behavior. | | `policy.allow()` | `[IMPLEMENTED]` | VM records an allow verdict with `nothing`. | | `policy.allow(value)` | `[IMPLEMENTED]` | VM records an allow verdict with the rendered value. | | `policy.reject(reason)` | `[IMPLEMENTED]` | VM records a reject verdict with the reason. | | `log.info(value)` | `[IMPLEMENTED]` | One argument; captured in the run report's logs. | | `log.warn(value)` | `[IMPLEMENTED]` | One argument; captured at warning level. | | `log.error(value)` | `[IMPLEMENTED]` | One argument; captured at error level. | | `log.debug(value)` | `[IMPLEMENTED]` | One argument; captured at debug level. | | `alert.send(text)` | `[REGISTRY-ONLY]` | One argument; the built-in host returns `E_CAP_MISSING` instead of pretending to deliver. | | `ai.prompt(text)` | `[POST-BASELINE]` `[REGISTRY-ONLY]` | One argument is recognized in this source snapshot; no built-in inference handler. | | `ai.complete(text)` | `[POST-BASELINE]` `[REGISTRY-ONLY]` | One argument is recognized in this source snapshot; no built-in inference handler. | | `ai.classify(text, classes)` | `[POST-BASELINE]` `[REGISTRY-ONLY]` | Two arguments are recognized in this source snapshot; no built-in classifier handler. | | `tool.call(name)` | `[POST-BASELINE]` `[REGISTRY-ONLY]` | One argument is recognized in this source snapshot; no built-in tool handler. | | `tool.call(name, input)` | `[POST-BASELINE]` `[REGISTRY-ONLY]` | Two arguments are recognized in this source snapshot; no built-in tool handler. | | `tool.run(name)` | `[POST-BASELINE]` `[REGISTRY-ONLY]` | One argument is recognized in this source snapshot; no built-in tool handler. | | `tool.run(name, input)` | `[POST-BASELINE]` `[REGISTRY-ONLY]` | Two arguments are recognized in this source snapshot; no built-in tool handler. | | MCP client/tool execution | `[UNSUPPORTED]` | No working built-in standalone Kaze MCP integration was established. | ### 4.6 Aliases and telemetry | Name | Tag | Resolution | | --- | --- | --- | | `lidar`, `camera`, `thermostat`, `probe` | `[IMPLEMENTED]` | Resource aliases resolve to the `sensor` family. | | `fan`, `mister`, `pump`, `relay`, `valve`, `motor`, `light` | `[IMPLEMENTED]` | Resource aliases resolve to the `device` family. | | Other unknown resource names | `[PARTIAL]` | Family resolution falls back to `device`; this does not prove a physical device exists. | | `tools` | `[POST-BASELINE]` `[REGISTRY-ONLY]` | Resolves to the `tool` family. | | `agent`, `model`, `llm` | `[POST-BASELINE]` `[REGISTRY-ONLY]` | Resolve to the `ai` family. | | Bare `battery` | `[PARTIAL]` | Recognized telemetry name; actual reading depends on the backend. | | Bare `altitude` | `[PARTIAL]` | Recognized telemetry name; actual reading depends on the backend. | | Bare `heading` | `[PARTIAL]` | Recognized telemetry name; actual reading depends on the backend. | | Bare `speed` | `[PARTIAL]` | Recognized telemetry name; actual reading depends on the backend. | | Bare `position` | `[PARTIAL]` | Recognized by the parser; the built-in simulator's telemetry lookup falls back to `0`. | | Bare `temperature` | `[PARTIAL]` | Recognized telemetry name; the standalone sensor backend is unavailable. | | Bare `humidity` | `[PARTIAL]` | Recognized telemetry name; the standalone sensor backend is unavailable. | | Bare `distance` | `[PARTIAL]` | Recognized telemetry name; the standalone sensor backend is unavailable. | | Bare `armed` | `[PARTIAL]` | Recognized telemetry name; returned representation depends on the backend. | | Bare `latitude` | `[PARTIAL]` | Recognized telemetry name; actual reading depends on the backend. | | Bare `longitude` | `[PARTIAL]` | Recognized telemetry name; actual reading depends on the backend. | | Bare `satellites` | `[PARTIAL]` | Recognized by the parser; the built-in simulator's telemetry lookup falls back to `0`. | | Bare-telemetry resolution | `[PARTIAL]` | Each source file must identify exactly one hardware resource resolving to `drone`, `rover`, or `sensor`; merged imports do not fix ambiguity in that file. | ## 5. Errors and recovery ### 5.1 Individual error codes `Catchable` means recoverable by a Kaze `try` block **when emitted by a capability call**. Front-end failures occur before that block runs. CLI option parsing can also produce unstructured usage text without a Kaze error code. | Code | Tag | Typical cause | Catchable? | | --- | --- | --- | --- | | `E_KAZE_PARSE` | `[IMPLEMENTED]` | Lexer or grammar failure, indentation, malformed literal, or parser nesting limit. | No | | `E_KAZE_CHECK` | `[IMPLEMENTED]` | Semantic check failure, undefined name, capability declaration, arity, or filter termination. | No | | `E_KAZE_COMPILE` | `[IMPLEMENTED]` | Compiler failure, including excessive item slots or list literal size. | No | | `E_KAZE_IMPORT` | `[IMPLEMENTED]` | Import cycle, collision, or invalid import resolution condition. | No | | `E_KAZE_ENTRY` | `[IMPLEMENTED]` | Missing explicitly selected item or ambiguous default routine. | No | | `E_KAZE_IO` | `[IMPLEMENTED]` | Source or imported-file I/O failure. | No | | `E_KAZE_FMT` | `[IMPLEMENTED]` | Formatter failure or refusal to preserve source token meaning. | No | | `E_KAZE_BADCODE` | `[IMPLEMENTED]` | Invalid, incompatible, truncated, or unverifiable bytecode. | No | | `E_KAZE_TRAP` | `[IMPLEMENTED]` | An executed bytecode trap. | No | | `E_KAZE_TYPE` | `[IMPLEMENTED]` | Invalid value type for an operation, field, index, or checked hardware argument. | No | | `E_KAZE_RANGE` | `[IMPLEMENTED]` | Invalid geographic place or an out-of-range checked physical argument. | No | | `E_KAZE_BOUNDS` | `[IMPLEMENTED]` | Invalid or out-of-range list, text, or point index. | No | | `E_KAZE_DIV0` | `[IMPLEMENTED]` | Division or remainder by zero. | No | | `E_KAZE_MATH` | `[IMPLEMENTED]` | Invalid real math, such as square root of a negative value. | No | | `E_KAZE_OVERFLOW` | `[IMPLEMENTED]` | Arithmetic or numeric operation produces a non-finite result. | No | | `E_KAZE_STACK` | `[IMPLEMENTED]` | Operand-stack or active recovery-handler limit exceeded. | No | | `E_KAZE_MEMORY` | `[PARTIAL]` | Arena or collection allocation fails; argument conversion has separate silent-`nothing` cases. | No | | `E_TIMEOUT` | `[IMPLEMENTED]` `[VERIFIED]` | Fuel exhaustion or an armed host deadline at a loop poll. | No | | `E_CAP_UNDECLARED` | `[IMPLEMENTED]` | Required family is absent from `needs:` at the runtime gate. | No | | `E_CAP_MISSING` | `[IMPLEMENTED]` `[POST-BASELINE]` | Any required family grant or configured backend is absent; unavailable built-in operations also return this code. | No | | `E_CAP_DENIED` | `[IMPLEMENTED]` `[POST-BASELINE]` | A policy is missing, malformed, unsupported, or denies the call; live drone actuation is disabled pending safety checks. | No | | `E_SAFETY_VIOLATION` | `[IMPLEMENTED]` | Safety error forwarded from an applicable host path. | No | | `E_KAZE_LINK` | `[IMPLEMENTED]` | Link connection, device configuration, or live I/O failure. | Yes, from a capability call | | `E_KAZE_LINK_TIMEOUT` | `[IMPLEMENTED]` | Live link did not respond within its applicable timeout. | Yes, from a capability call | | `E_COMMAND_REJECTED` | `[IMPLEMENTED]` | A vehicle/backend rejected a command. | Yes, from a capability call | | `E_ARMING_DENIED` | `[IMPLEMENTED]` | The vehicle did not reach the armed state or denied arming. | Yes, from a capability call | | `E_KAZE_HOST` | `[IMPLEMENTED]` | Explicitly classified operational host failure. | Yes, from a capability call | | `E_KAZE_HOST_UNCLASSIFIED` | `[IMPLEMENTED]` `[POST-BASELINE]` | An unknown or untyped host failure is not silently treated as a recoverable operational error. | No | ### 5.2 Error behavior | Item | Tag | Behavior | | --- | --- | --- | | `try` recovery set | `[IMPLEMENTED]` | Exactly `E_KAZE_LINK`, `E_KAZE_LINK_TIMEOUT`, `E_COMMAND_REJECTED`, `E_ARMING_DENIED`, and `E_KAZE_HOST` are catchable from capability calls. | | Unknown host error codes | `[IMPLEMENTED]` `[POST-BASELINE]` `[VERIFIED]` | Unknown or untyped host failures become `E_KAZE_HOST_UNCLASSIFIED`, which is not catchable. | | Stack unwind | `[IMPLEMENTED]` | A caught error unwinds the operand stack and restores the verdict that existed at `try` entry; local changes are not rolled back. | | Error location | `[PARTIAL]` | Parser errors have line/column; other failures may report an item line or line `0` where finer source location is unavailable. | | JSON run success | `[IMPLEMENTED]` | `--json` produces a run report containing entry, value, actions, logs, instruction/fuel counts, ticks, optional verdict, and `simulated_families`. | | JSON run failure | `[PARTIAL]` | `kaze run --json` still prints failures as text to stderr instead of a corresponding JSON diagnostic object. | | CLI exits | `[IMPLEMENTED]` | Successful `run` exits `0`; execution/front-end errors exit `1`; usage/flag errors exit `2`. | | Required parameter diagnostics | `[TARGET]` `[PARTIAL]` | Repository policy requires structured guidance, but standalone Kaze can bind missing input to `nothing` and later raise `E_KAZE_TYPE`. | ## 6. Execution limits and bytecode | Limit or property | Tag | Current behavior | | --- | --- | --- | | Instruction fuel | `[IMPLEMENTED]` `[VERIFIED]` | Default `200,000` units shared by entry and hooks in one run; `--fuel` changes it. A requested `0` becomes `1`. | | String arena | `[IMPLEMENTED]` | Default `256 KiB` of string bytes; runtime allocation can raise `E_KAZE_MEMORY`. | | Collection heap | `[PARTIAL]` | Default `65,536` stored values; this counts collection values, not all allocation bytes or empty collection objects. | | Operand stack | `[IMPLEMENTED]` | Maximum `256` values. | | Active `try` handlers | `[IMPLEMENTED]` | Maximum `32` active recovery handlers per item. | | Parser expression nesting | `[IMPLEMENTED]` | Maximum `64` guarded expression levels. | | Parser block nesting | `[IMPLEMENTED]` | Maximum `64` block levels. | | Item local slots | `[IMPLEMENTED]` | Up to `255` compiled slots per item, including parameters and compiler-generated temporaries. | | List literal elements | `[IMPLEMENTED]` | Up to `255` elements in one source literal. | | Capability-call arguments | `[IMPLEMENTED]` | Bytecode encodes at most `255`; each registered operation usually has a much smaller arity in §4. | | Link silence window | `[IMPLEMENTED]` | Between `1` and `4,294,967,295` milliseconds; larger/shorter values are refused. | | Ticks | `[IMPLEMENTED]` | Default `0`; `--ticks` accepts an unsigned 32-bit value. | | Tick interval | `[IMPLEMENTED]` | Default `100` ms; `--tick-ms` accepts an unsigned 64-bit value. | | Tick cleanup | `[IMPLEMENTED]` | String arena and collection heap are cleared after each supervisor tick; VM values do not persist across tick boundaries. | | Blocking host call | `[PARTIAL]` | Fuel counts VM instructions, not time spent inside a blocking host call. | | Host deadline | `[PARTIAL]` | An embedding host can arm the process-global deadline; loop-head polling checks it. The CLI does not expose a general deadline flag. | | `.kazebc` format | `[IMPLEMENTED]` `[VERIFIED]` | Standalone version `4`; a compiled module contains flattened items, not runtime imports. | | Bytecode verifier | `[IMPLEMENTED]` | Deserialization and execution validate structure, opcodes, indices, jumps, capability arity, and stack flow before execution. | | Deterministic artifact | `[IMPLEMENTED]` `[VERIFIED]` | Repeated compilation of the same source/layout produced identical bytes locally; recorded external absolute paths can affect artifact origins. | | Sofuu embedded artifact | `[UNSUPPORTED]` | Embedded source format `2` (and legacy format `1`) and standalone format `4` are not directly interchangeable. | | Security compatibility | `[POST-BASELINE]` | The new gate and host defaults change which previously accepted runs succeed; bytecode format remains `4`. A release/version compatibility decision remains open. | ## 7. Configuration and command line ### 7.1 Commands | Command | Tag | Behavior | | --- | --- | --- | | `kaze run ` | `[IMPLEMENTED]` | Parse, resolve imports, check, compile, verify, and execute source. | | `kaze run ` | `[IMPLEMENTED]` `[VERIFIED]` | Deserialize, verify, and execute standalone format-4 bytecode. | | `kaze check ` | `[IMPLEMENTED]` | Prepare/check source and imports without executing the program. | | `kaze compile ` | `[IMPLEMENTED]` | Emit `.kazebc`; `--out` chooses the path. | | `kaze fmt ` | `[IMPLEMENTED]` | Print formatted source; `--check` and `--write` change formatter behavior. | | `kaze bench ` | `[IMPLEMENTED]` | Repeatedly run a prepared source or module and report timing; run only with policy-compliant workloads. | | `kaze selftest` | `[IMPLEMENTED]` `[POST-BASELINE]` | Run the scorecard using pure computation, bytecode validation, and gate refusals; it no longer implicitly runs a simulated mission. | | `kaze repl` | `[IMPLEMENTED]` | Interactive buffer and commands, subject to the same backend limitations. | | `kaze version` | `[IMPLEMENTED]` `[VERIFIED]` | Print `kaze 1.0`. | | `kaze --version` | `[IMPLEMENTED]` `[VERIFIED]` | Alternative version command. | | `kaze --help` | `[IMPLEMENTED]` | Print CLI help. | | `kaze-lsp` | `[IMPLEMENTED]` | Separate language-server binary over stdio; see [TOOLING.md](TOOLING.md). | ### 7.2 CLI options | Option | Tag | Default / meaning | | --- | --- | --- | | `--entry NAME` | `[IMPLEMENTED]` | Entry name; default uses root `main`, then sole root routine. | | `--arg NAME=VALUE` | `[IMPLEMENTED]` `[VERIFIED]` | Repeatable argument. Parse value as JSON when possible; otherwise use text. | | `--arg 0=VALUE` | `[IMPLEMENTED]` | Numeric key binds by zero-based parameter position if no named binding takes precedence. | | `--cap FAMILY` | `[IMPLEMENTED]` `[POST-BASELINE]` | Repeatable family grant. It does not implicitly select a simulator or provide a missing backend. | | `--cap FAMILY=BACKEND` | `[PARTIAL]` | Grant and choose a backend; the standalone live host handles `drone` and `device`, with specific mapping requirements. | | `--cap drone=sim` | `[SIMULATED]` `[POST-BASELINE]` | Explicitly select the labelled drone simulator for testing. | | `--cap rover=sim` | `[SIMULATED]` `[POST-BASELINE]` | Explicitly select the labelled rover simulator for testing. | | Drone UDP backend | `[LIVE-PATH]` `[UNVERIFIED]` | `--cap drone=udp:HOST:PORT` binds a local UDP endpoint for MAVLink. | | Drone UART backend | `[LIVE-PATH]` `[UNVERIFIED]` | `--cap drone=uart:/dev/device@baud`; omitting `@baud` selects `57600`. Requires the `uart` build feature. | | `--pin NAME=LINE` | `[LIVE-PATH]` `[UNVERIFIED]` | Map a name to an unsigned 16-bit Linux GPIO line. | | `--pwm NAME=CHIP:CHANNEL` | `[LIVE-PATH]` `[UNVERIFIED]` | Map a name to unsigned 16-bit PWM chip/channel numbers. | | `--fuel N` | `[IMPLEMENTED]` | Unsigned instruction budget; default `200000`, with a minimum effective value of `1`. | | `--ticks N` | `[IMPLEMENTED]` | Unsigned tick count; default `0`. | | `--tick-ms N` | `[IMPLEMENTED]` | Unsigned tick interval in milliseconds; default `100`. | | `--pace` | `[IMPLEMENTED]` | Sleep between ticks; disabled by default. | | `--sim K=V[,K=V]` | `[SIMULATED]` | Repeatable simulator-state overrides; requires an explicit `drone=sim` or `rover=sim` testing backend. | | `--no-policy` | `[IMPLEMENTED]` `[POST-BASELINE]` | Disables loading the policy file; capability calls still fail closed with `E_CAP_DENIED`. Pure computation can run. | | `--json` | `[IMPLEMENTED]` | JSON success report for `run`, timings for `bench`, and scorecard output where supported. | | `--plain` | `[IMPLEMENTED]` | Plain-text run report. | | `--out PATH`, `-o PATH` | `[IMPLEMENTED]` | Output path for `compile`. | | `--disasm` | `[IMPLEMENTED]` | Print compiled module disassembly instead of writing the artifact. | | `--check` | `[IMPLEMENTED]` | For `fmt`, report whether input is already formatted. | | `--write`, `-w` | `[IMPLEMENTED]` | For `fmt`, write formatted source to the file. | | `--iterations N` | `[IMPLEMENTED]` | For `bench`, number of iterations; default `20`, minimum effective value `1`. | | `--help`, `-h`, `help` | `[IMPLEMENTED]` | Help flag recognized by the shared flag parser; command-specific help behavior varies. | | `--config PATH` | `[UNSUPPORTED]` | The standalone `kaze` CLI has no agent configuration-file option. Its flag parser treats unrecognized tokens as positionals rather than rejecting every unknown flag. | | Positional routine values | `[UNSUPPORTED]` | The CLI uses the first positional as the source/artifact path; routine values use `--arg`. | ### 7.3 Argument, policy, and environment configuration | Setting | Tag | Current behavior | | --- | --- | --- | | Named JSON argument | `[IMPLEMENTED]` | `--arg amount=4`, `--arg enabled=true`, `--arg 'items=[1,2]'`, and `--arg 'item={"x":1}'` become the corresponding values. | | Text argument | `[IMPLEMENTED]` | If `VALUE` is not valid JSON, its raw text becomes a string. Quote shell arguments as needed. | | Duplicate argument key | `[IMPLEMENTED]` | The later `--arg` replaces the earlier value for the same key. | | Named vs numeric key | `[IMPLEMENTED]` | For a parameter, its named key is checked before its zero-based numeric key. | | Missing argument | `[PARTIAL]` `[VERIFIED]` | Becomes `nothing`; later use can fail with `E_KAZE_TYPE`. No early structured missing-input guidance. | | Argument allocation failure | `[PARTIAL]` | Conversion can substitute `nothing` when allocating an argument fails. | | `policy.json` | `[IMPLEMENTED]` `[POST-BASELINE]` | The CLI reads this file from the current working directory. A valid file is required for capability calls; pure computation does not require one. | | Policy deny entry | `[IMPLEMENTED]` `[POST-BASELINE]` | `deny` must be an array of known `family.operation`, `family.*`, or `*` patterns; `drone.link_lost` is also recognized. | | Malformed policy | `[POST-BASELINE]` `[IMPLEMENTED]` | The gate rejects missing/empty objects, malformed JSON, unknown fields, non-text entries, and unknown deny patterns; CLI parsing also rejects duplicate keys. | | `KAZE_GPIO_ROOT` | `[LIVE-PATH]` | Override the Linux GPIO sysfs root used by the hardware bus. | | `KAZE_GPIO_CHIP` | `[LIVE-PATH]` | Override the GPIO character-device path used by applicable hardware code. | | `KAZE_PWM_ROOT` | `[LIVE-PATH]` | Override the Linux PWM sysfs root used by the hardware bus. | | UART feature | `[IMPLEMENTED]` | Serial transport requires building with the `uart` Cargo feature. | | GPIO character-device feature | `[IMPLEMENTED]` | Character-device GPIO is behind the `chardev` Cargo feature. | | `AGENT_` routine binding | `[UNSUPPORTED]` `[TARGET]` | Required by repository policy for standalone agent binaries; not implemented by this standalone `kaze` CLI. | | `SOFUU_*` routine binding | `[UNSUPPORTED]` `[TARGET]` | Part of the repository's standalone-agent configuration target, not standalone `kaze` CLI parameter resolution. | | `./agent.config.json` | `[UNSUPPORTED]` `[TARGET]` | Part of the standalone-agent target; not loaded for Kaze CLI routine binding. | | Signature defaults | `[UNSUPPORTED]` `[TARGET]` | The repository lists signatures at the bottom of the intended precedence hierarchy; current standalone signatures have no defaults. | | Intended agent precedence | `[TARGET]` | CLI flags/positionals > `AGENT_` / `SOFUU_*` environment > config file > routine signature. A Sofuu-compiled agent is a separate implementation and must be verified separately. | ### 7.4 Simulator state options All entries in this table are `[SIMULATED]` and are not real telemetry. Their use is constrained by `RULES.md` §1.9. These are documented to describe existing source behavior, not as a recommendation for non-robotics execution. | `--sim` key | Tag | Default / interpretation | | --- | --- | --- | | `battery` | `[SIMULATED]` | `100`. | | `armed` | `[SIMULATED]` | `false`; `true`, `1`, or `yes` are treated as true. | | `on_ground` | `[SIMULATED]` | `true`; same boolean parsing as `armed`. | | `altitude` | `[SIMULATED]` | `0` meters. | | `lat` | `[SIMULATED]` | `0`. | | `lon` | `[SIMULATED]` | `0`. | | `heading` | `[SIMULATED]` | `0`. | | `speed` | `[SIMULATED]` | `0`. | | `temperature` | `[SIMULATED]` | `22`. | | `humidity` | `[SIMULATED]` | `45`. | | `distance` | `[SIMULATED]` | `2`. | | `front_distance` | `[SIMULATED]` | Alias that sets simulated distance. | | `link_lost_after` | `[SIMULATED]` | No dropout by default; accepts a nonnegative millisecond time. | | `link-lost-after` | `[SIMULATED]` | Alias for `link_lost_after`. | | `link_lost` | `[SIMULATED]` | Alias for `link_lost_after`. | ### 7.5 REPL commands | Command | Tag | Behavior | | --- | --- | --- | | `.help` | `[IMPLEMENTED]` | Show REPL command help. | | `.needs family, ...` | `[IMPLEMENTED]` | Add declarations used when the buffer has no `needs:` header. | | `.cap family` | `[IMPLEMENTED]` `[POST-BASELINE]` | Grant the family; this does not select a simulator. The REPL reads `policy.json` for capability calls. | | `.cap drone=sim` / `.cap rover=sim` | `[SIMULATED]` `[POST-BASELINE]` | Explicitly grant and select a labelled robotics simulator for testing. | | `.run [routine]` | `[PARTIAL]` | Run buffered source with optional entry; default run options do not bind routine arguments. | | `.clear` | `[IMPLEMENTED]` | Clear the buffer, declarations, and grants. | | `.list` | `[IMPLEMENTED]` | Print declarations and buffered source. | | `.exit`, `.quit` | `[IMPLEMENTED]` | Leave the REPL. | ## 8. Evidence and maintenance | Evidence | Tag | Scope | | --- | --- | --- | | Offline build | `[VERIFIED]` | The current source compiled locally into a temporary target directory without downloading dependencies or model weights. | | Pure language probes | `[VERIFIED]` | Version, named arguments, loops, arithmetic, points, mixed-unit behavior, literal modulo ambiguity, missing inputs, fuel, imports, and format-4 artifacts. | | Capability safety tests | `[VERIFIED]` `[POST-BASELINE]` | Local logging, policy/grant refusals, unavailable backends, link-loss gating, physical-argument refusals, lazy link setup, and disabled live drone actuation were checked; drone and rover simulation were explicitly selected and labelled. | | Compatibility and language tests | `[VERIFIED]` `[POST-BASELINE]` | Selected format-4 compatibility, module, REPL, benchmark, standard-library, and language tests passed with explicit policy and grants; robotic simulation was explicitly selected and labelled. | | Capability examples | `[VERIFIED]` | Filter and drone recovery examples, all 40 registry operations in expression position, and the dotted-log statement limitation were checked by the front end only; their capabilities were not executed. | | Real external operations | `[UNVERIFIED]` | No AI, MCP, external tool, memory backend, or physical hardware was exercised for this inventory. | | Full release gates | `[UNVERIFIED]` `[PARTIAL]` | The full test, contract, and preflight suites include non-robotics stand-ins that must be migrated before they can run under `RULES.md` §1.9. Distribution artifacts have existing verification failures. | | Published build | `[UNVERIFIED]` | This source snapshot is not proof of the contents of any published binary. | Primary implementation sources: [lexer](../src/lexer.rs), [parser](../src/parser.rs), [AST](../src/ast.rs), [checker](../src/checker.rs), [compiler](../src/compiler.rs), [values](../src/value.rs), [VM](../src/vm.rs), [capability registry](../src/caps.rs), [hardware gate](../src/hardware.rs), [host dispatch](../src/host.rs), [bytecode](../src/isa.rs), [run API](../src/lib.rs), and [CLI](../src/main.rs). The existing [specification](SPEC.md), [module reference](MODULES.md), [compatibility notes](COMPATIBILITY.md), and [tooling reference](TOOLING.md) provide additional context; where they differ, the gaps are tagged above. --- # API reference URL: https://docs.sofuu.xyz/api/ 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. Sofuu is at **0.3.0-beta**. Signatures are documented shapes, not frozen ABI. The funnel list in `docs/EMBEDDING.md` bounds what an embedded host may call; anything outside it carries no stability contract. ## ai | Method | Shape | Notes | | --- | --- | --- | | `complete` | `complete(prompt, config?)` → `Promise<{text, usage, raw}>` | `usage` is `{promptTokens, completionTokens}`. Messages accept an `images` array. | | `stream` | `stream(prompt, config?)` → `AsyncIterator` | Yields chunks as they arrive; each carries `.text`. | | `embed` | `embed(text, config?)` | Defaults to the local `sem2-64` space at **64 dimensions**. Explicit providers may need network access. | | `embedBatch` | `embedBatch(texts[], config?)` | Local-only batch; one `Float32Array` per input. | | `embedImage` | `embedImage(bytes)` | `Uint8Array` bytes to a 64-dimensional unit vector in the joint text-image space. | | `embedLocal` | `embedLocal(text)` | Bundled offline embedding, synchronous, no network: **768 dimensions**. | | `similarity` | `similarity(a, b)` | Cosine similarity over native SIMD kernels. | | `dot` / `l2` | `dot(a, b)` / `l2(a, b)` | Dot product and L2 distance over the same kernels. | | `estimateTokens` | `estimateTokens(text)` | Fast count estimate for prompt budgeting. | `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 | | --- | --- | --- | | `createServer` | `createServer(handler)` → server | Non-blocking server over OS sockets. The handler receives `req` and `res`. | | `listen` | `server.listen(port, host)` | Binds and refs the handle; `unref()` and `ref()` control loop holding. | | `fetch` | `fetch(url, opts?)` | Client over statically linked curl, resolving to `.text()` and `.json()`. Also global `fetch`. | | `serve` | `serve({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` / `exists` | `readdir(path)`, `mkdir(path)`, `rm(path)`, `exists(path)` | Directory listing, creation, removal, and existence. | | `setRoot` / `clearRoot` | `setRoot(path)` / `clearRoot()` | Confines relative reads to a root. Absolute paths and symlink escapes are refused while a root is set. | | `spawn` | `spawn()` | Global, not an `fs` member: launches a child process with an argument list and returns its output. | ## web | Method | Shape | Notes | | --- | --- | --- | | `search` | `search(text)` | Keyless web search; returns ranked result snippets. | | `open` | `open(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 | | --- | --- | --- | | `open` | `open(path, vecDim, options?)` | Opens a QTSQ container. `options.adapter` routes to `qdrant`, `pinecone`, or `pgvector`; `options.plaintext` selects an explicit zero-KDF open. | | `remember` | `remember(vectorOrText, text?, role?, turn?)` | Stores vector, timestamp, and text. A plain string is embedded for you. | | `recall` | `recall(queryVectorOrText, k)` | Top `k` records with `distance` (0 is an exact match) and `similarity`. | | `count` / `stats` | `count()` / `stats()` | Record total and capacity metrics; `stats()` returns JSON text. | | `flush` / `forget` / `close` | `flush()`, `forget(...)`, `close()` | Durability and lifecycle. Opening a file another writer holds is refused with `E_LOCKED`. | | `list` / `export` | `list(opts)` / `export()` | Paged listing and unencrypted export. | | `rememberWorking` / `promoteWorking` / `clearWorking` | see 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. ## tools | Method | Shape | Notes | | --- | --- | --- | | `execute` | `execute(name, args)` | Runs a builtin or host tool in-process behind the policy layer. | | `list` / `describe` | `list()` / `describe(name)` | Inventory and schema, including policy verdicts. | | `mcpResult` | `mcpResult(result, meta)` | Maps an MCP result into `{ok, text, data?, error?, meta}`. | | `PACKS` | `PACKS.coding` / `.web` / `.memory` / `.system` | Toolpacks 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 | | --- | --- | --- | | `define` | `define({name, system?, tools, budget?})` → handle | Validates the tool list; an unknown name or duplicate agent name throws. | | `run` | `run(handleOrNameOrDef, task, opts?)` → `Promise` | The execution loop. Requires a configured model provider. | | `list` / `cancel` | `list()` / `cancel(id)` | Enumerate and cancel runs. | | `renderTrace` | `renderTrace(result)` | Step trace. | | `resolveApproval` / `pendingApprovals` | `resolveApproval(id, allow, always)` / `pendingApprovals()` | Settles a host approval request. | ## mcp | Method | Shape | Notes | | --- | --- | --- | | `connect` | `connect("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. | | `call` | `call(method, params, {timeoutMs})` | Per-call deadline; on expiry the client sends `notifications/cancelled`. | | `listTools` / `listResources` | `listTools()` / `listResources()` | Follows `nextCursor` and returns the full inventory. | | `serve` | `serve({name, version})` → server | Server object with `tool`, `resource`, `prompt`, `use`, `start`, and `stop`. | | `loadConfig` | `loadConfig()` | Reads `~/.sofuu/mcp.json`, overridable with `SOFUU_MCP_CONFIG`. A corrupt file is reported and left in place. | | `serverTool` / `serverStart` / `serverStop` | funnel 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` / `clearInterval` | Native event-loop timers. | | `sleep(ms)` | Synchronous halt of the whole event loop. Avoid in a server. | | `console.log` / `console.time` / `console.timeEnd` | Standard 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`, `Response` | | Web platform globals | `structuredClone`, `Blob`/`File`/`FormData`, `Event`/`EventTarget`/`CustomEvent`, `MessageChannel`/`MessagePort`, `navigator`, persistent `localStorage` backed by `.sofuu/localStorage.json` | | Web Crypto | `crypto.randomUUID()` from OS entropy, `crypto.getRandomValues()`, `crypto.subtle.digest("SHA-256")` | | Streams | `ReadableStream`, `WritableStream`, `TransformStream`, `TextDecoderStream`, `TextEncoderStream`; `Response.body` is a stable `ReadableStream` | | `node:fs` | `readFileSync`, `writeFileSync`, `existsSync`, `readdirSync`, `mkdirSync`, `unlinkSync`, `statSync`, `promises` | | `node:path` | `join`, `resolve`, `normalize`, `isAbsolute`, `relative`, `dirname`, `basename`, `extname`, `parse`, `format`, `sep` | | `node:buffer` | `Buffer.from`, `alloc`, `concat`, `isBuffer`, `byteLength`, `toString`, `copy`, `slice` | | `node:events` | `EventEmitter` with `on`, `once`, `off`, `emit`, `listeners`, `listenerCount`, `setMaxListeners` | | `node:process` | `nextTick`, `version`, `platform`, `arch`, `versions` | | AI 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](/server/) covers `createServer` and `sofuu serve`; [troubleshooting](/troubleshooting/) maps error codes to checks. --- # Troubleshooting URL: https://docs.sofuu.xyz/troubleshooting/ Failures usually surface as a subsystem refusal, not a crash. This page maps documented symptoms to a check and a fix. ## Start with doctor ```bash sofuu doctor ``` `doctor` prints sections for QTSQ linkage, the brain file, the resolved context window, config and API key state, protocol probes, and capabilities. It exits non-zero on failure and treats a store held by another process as busy, not broken. `doctor --json` emits the same entries as structured output. ## Quick map | Symptom | Check | Fix | | --- | --- | --- | | Installer stops at platform detection | `uname -s`, `uname -m` | Published platform or source build. | | Installer stops at checksum | `sha256sum -c` / `shasum -a 256 -c` | Re-download; do not bypass verification. | | Local model does not load | File format, OS libraries | Supported file, provider plugin, or remote endpoint. | | `E_DIM` on recall | Dimension in `doctor` output | Reopen with the store's space and dimension. | | MCP connect fails | `sofuu mcp test ""` | Fix the command, transport, or secret. | | Compile refuses a profile or base | `--profile`, `--base` | Valid profile name, existing base binary. | ## Install **Unsupported platform.** The installer maps `uname -m` to `arm64` or `x86_64` and `uname -s` to `darwin` or `linux`, and exits otherwise. Published builds cover macOS arm64 and Linux x86_64 / arm64; other targets need a [source build](/build/). **Checksum or signature failure.** The script verifies the archive and the extracted binary, and refuses to run without `sha256sum` or `shasum`. A mismatch means a corrupted or substituted download; fetch it again. **Missing from `PATH`.** The install lands in `/usr/local/bin` when writable, otherwise `~/.local/bin` when it is on `PATH`. Start a new shell, or set `SOFUU_INSTALL_DIR` and add it to `PATH`. ## Provider configuration **No API key.** `doctor` warns that the active provider has no key and that providers will answer `401`. Keys live in `~/.sofuu/config.json`, with `OPENAI_API_KEY` and `ANTHROPIC_API_KEY` as fallback. **Wrong base URL.** An OpenAI-compatible endpoint needs the version path, for example `http://127.0.0.1:11434/v1`. Check the port and the path; `doctor` prints the endpoint it resolved. Set both with `/model` and `/provider`. ## Local inference (preview) The built-in GGUF and SafeTensors engine is an experimental preview: loading depends on the model file and the OS libraries present. Confirm the extension and that the path resolves from the working directory. If it still fails, use the `llamacpp` provider plugin or a remote endpoint. ## Memory **Wrong dimension (`E_DIM`).** `memory.open(path, vecDim)` fixes the dimension, and every stored or queried vector must match. `sofuu.ai.embed()` produces 64 dimensions; `sofuu.ai.embedLocal()` produces 768. `doctor` prints the store's declared space and dimension. **Wrong key.** A store from another machine, or one whose `~/.sofuu/brain.key` was lost, refuses with a message naming the file as a container this key cannot open. Restore the key file or set `SOFUU_BRAIN_KEY` to its exact 64-hex-character value; without a backup there is no recovery. **Plaintext mode.** `{ plaintext: true }` is a deliberate zero-KDF open, not a recovery path. `doctor` reports whether the brain is encrypted under the machine key or still on the legacy password. Start a new file rather than toggling the flag on an existing store. **Store busy (`E_LOCKED`).** One writer at a time. A `sofuu serve` process or a second agent holding the brain produces this refusal; `doctor` reports it as a skipped check. Close the other process. ## MCP **Stdio command not found.** The client spawns that command. `sofuu mcp test ""` reports the handshake, protocol version, and tool count; confirm its interpreter (`npx`, for example) is on `PATH`. An unresolvable `{"secret":"NAME"}` refuses the connect. **Wrong transport.** A bare `{url}` means Streamable HTTP. A legacy HTTP+SSE endpoint must request `transport: 'sse'`; the client does not infer it. **Session expiry or a lost reply.** Streamable HTTP carries an `Mcp-Session-Id` and deletes it on disconnect: reconnect and re-list tools. A request queued for reconnection never ran; one already dispatched that loses its reply is outcome-unknown, so verify the effect before retrying. ## Compiler **Profile.** `--profile` accepts `lean`, `full`, and `micro` (also `mcp`). Flags select one base; the last wins, and an unknown name is rejected. The micro base omits the agent loop and inference. **Missing base.** `--base ` must be an existing executable; a missing path fails instead of falling back. A cross-target build appends to a base built for that target, so that build's toolchain must exist. **Kaze mismatch.** The embedded engine reports 0.1 and writes bytecode format 2; standalone Kaze is 1.0 with format 4. Bytecode is not interchangeable, and a compiled Kaze agent refuses an incompatible runtime base. ## Runs and resume `sofuu logs` lists runs and status; `sofuu logs --last-error` prints the post-mortem card: failed step, code, context snapshot, and a recovery hint. `sofuu resume ` continues from the newest valid checkpoint; a redacted or truncated one is refused, and `--step=N` targets a step. ## What to include in a bug report - The full `sofuu version` line: version, commit revision, QuickJS version, architecture. - Platform and install path, plus `sofuu doctor --json` with keys and private paths redacted. - The smallest reproduction: the file, the exact command, and the exit status. - For model failures, the file format — not the weights; for MCP failures, the server command or URL, transport, and negotiated protocol version. File issues at [github.com/sofuu-runtime/sofuu/issues](https://github.com/sofuu-runtime/sofuu/issues).