# Affordance: all documentation This file is every documentation page of https://affordance.rs/ as Markdown, in reading order. A shorter summary is at https://affordance.rs/llms.txt. --- Source: docs/GETTING_STARTED.md Page: https://affordance.rs/docs/getting-started.html # Getting started You need Rust 1.89 or later. It runs on Linux and macOS; see [platform evidence](DEVELOPING.md#current-platform-evidence). Python, Node and model weights are not needed. ## Install ```sh cargo install affordance ``` This installs one command, `affordance`. Everything below uses it; you do not write Rust to build an app. Or run it without installing anything, with [uv](https://docs.astral.sh/uv/) (Python's package runner). Put `uvx` in front of each `affordance` command below: ```sh uvx affordance init my-agent ``` The example apps are in the repository: ```sh git clone https://github.com/approximatelabs/affordance && cd affordance ``` ## Render an app ```sh echo '{"name":"world"}' | affordance render views/demo/hello.tsx --state - ``` It prints `Hello, world! [greet]` and its spans. The greeting span marks text; the `greet` span marks a visible action and the handler it runs. `--json` prints `ids` and `spans` for another program. With no `--tokenizer`, `render` uses its bundled default (GPT-2), enough for an app that writes no model-specific chat format. The app is [views/demo/hello.tsx](../views/demo/hello.tsx): ```tsx export default function Hello({name = "world"}) { return {`Hello, ${name}!`} ({name})}>{" [greet]"} ; } ``` This is Affordance's TypeScript/JSX subset, interpreted in Rust (not React or Node). A render evaluates the app against its state, then layout decides its exact token IDs and the actions that survive. An action's handler changes the state; the next render shows it. See [the language](../spec/LANGUAGE.md). ## Your first agent ```sh affordance init my-agent cd my-agent ``` `init` writes these files: - `app.tsx`: the agent. It shows the model its task and the log of what it has seen and done, offers a `shell` tool and an `answer` tool, and loops until the model answers. - `affordance.yaml`: where it runs. A model server (any OpenAI-compatible server on `127.0.0.1:8080`), a machine (`home`: this machine's shell) and the agent with its task. - `.gitignore`: the run's journals (`.affordance/`) and local settings (`affordance.local.yaml`). - `affordance.d.ts` and `tsconfig.json`: types for your editor (what `harness`, `model()`, the hooks and the elements are), so it completes and checks the app. They describe the platform; nothing runs them. Start a model server. No key is needed for a local one: ```sh llama-server -m your-model.gguf --port 8080 --jinja # llama.cpp # or: ollama serve (then use --set model.url=http://127.0.0.1:11434/v1 --set model.model=) # or: vllm serve --port 8080 --served-model-name local --enable-auto-tool-choice --tool-call-parser hermes ``` Then run the agent: ```sh affordance run ``` `affordance run` finds `affordance.yaml` in the current directory (or a parent), runs the agent and prints a report when it stops: `"stopped": {"answer": "..."}`. The agent's tools reach the model as tool definitions, so the server must parse tool calls. That is what `--jinja` (llama.cpp) and `--tool-call-parser` (vLLM, SGLang; the parser's name depends on the model) turn on. If the server returns a tool call as plain text, `affordance run` says so. If the server is not reachable, `affordance run` says so and keeps trying for five minutes (`model.retry.for_s`). Each agent's journal and trace are in `.affordance//`. The journal records every input the agent received, so `affordance run --resume` continues the run exactly; `affordance run --fresh` starts over. ### Change a setting - For one run: `affordance run --set model.url=http://other:8080/v1 --set model.context=32768`. A key is a dotted path; a value is YAML. - For this machine only: put it in `affordance.local.yaml` beside `affordance.yaml` (it is not committed). It layers over the main file. - From the environment: write `${VAR}` or `${VAR:-default}` in a value. - To see what the run will use: `affordance config` prints the resolved deployment, secrets hidden. A hosted API takes its key from an environment variable (read at each call, never written to the journal): ```yaml model: kind: chat url: https://api.example.com/v1 model: some-model context: 128000 key_env: EXAMPLE_API_KEY ``` See [model bindings](MODEL_BINDINGS.md) for SGLang and vLLM token-id serving, Anthropic and OpenAI Responses, and [running agents](RUNTIME.md) for the full deployment format. ## The library An app imports the bundled TSX library with `@affordance/` paths: ```tsx import { useLog } from "@affordance/lib/log.tsx"; import { ModelContext } from "@affordance/lib/model.tsx"; ``` `@affordance/` names the library as an import map names a package: the copy bundled with the `affordance` command, or a directory the deployment names with `library: path/to/views`. Your own files import each other by relative path. ## Next - **Write apps:** [running agents](RUNTIME.md), [the language and layout](../spec/LANGUAGE.md), and the apps in [`views/demo/`](../views/demo). - **Add HTTP or MCP:** [Fetch and MCP](HTTP_AND_MCP.md). - **Embed the engine in a Rust program** (not needed to build apps): the [harness guide](HARNESS_GUIDE.md) and [examples/embedding/hello.rs](../examples/embedding/hello.rs) (`cargo run --release --example hello -- TOKENIZER.json`). - **Contribute:** [contributing](../CONTRIBUTING.md) and [development](DEVELOPING.md). --- Source: examples/first_agent/README.md Page: https://affordance.rs/docs/first-agent.html # A first agent An agent that reads its task, may run shell commands on this machine, and stops when it answers. `app.tsx` is the whole app; `affordance.yaml` binds it to a model server and a machine. `affordance init` writes these same two files into a new directory. ## Run it 1. Start an OpenAI-compatible model server on port 8080. No key is needed: ```sh llama-server -m your-model.gguf --port 8080 --jinja # llama.cpp # or: vllm serve --port 8080 --served-model-name local --enable-auto-tool-choice --tool-call-parser hermes # or: ollama serve (then add --set model.url=http://127.0.0.1:11434/v1 --set model.model=) ``` Set `context` in `affordance.yaml` to your model's context length (the server's `-c`). 2. Run the agent from this directory: ```sh affordance run ``` The report prints when the agent stops: `"stopped": {"answer": "..."}`. It stops when it calls `answer`, or when it replies with no tool call (that reply is then the answer). Its journal and trace are in `.affordance/first/`; `affordance run --resume` continues the run, `--fresh` starts over. For a hosted API, set `url`, `model` and `context`, and `key_env: NAME` for the environment variable that holds its key. `affordance config` shows what a run will use. `tests/first_agent.rs` runs this example, as written, against a stand-in server. --- Source: examples/README.md Page: https://affordance.rs/docs/examples.html # Examples An Affordance app is a folder with an `app.tsx` and an `affordance.yaml`, run with `affordance run` in that folder. You do not write Rust to build one. - **[first_agent/](first_agent/README.md)**: start here. A complete agent in one TSX file: it reads its task, may run shell commands on your machine, and stops when it answers. `affordance run` in its folder runs it against a local model server (llama.cpp, Ollama, vLLM) or a hosted API. `affordance init` writes a copy to start from. - More apps: a long-session agent with context folding ([`views/agents/session.tsx`](../views/agents/session.tsx)), and in [`views/demo/`](../views/demo) a chat, a research agent comparing context policies, a memory that outlives its sessions, and a recursive language model (RLM). Only if you are embedding the engine in your own Rust program: - **[embedding/hello.rs](embedding/hello.rs)**: load an app and a tokenizer, render it, call an action and render the result, from Rust (`cargo run --release --example hello -- TOKENIZER.json`). --- Source: docs/DESIGN.md Page: https://affordance.rs/docs/design.html # Why Affordance is shaped like a browser This document explains where the line between the engine and an app is, and why. It is for anyone extending Affordance, person or model, who wants to predict the answer to "where does this feature go?" before asking. The contracts are in [spec/](../spec/CONTRACTS.md); this is the reasoning behind them, shown through decisions that were actually made. ## The claim A web browser renders the internet's state into pixels for a person, and lets the page react to what the person does. Affordance renders an app's state into tokens for a model, and lets the app react to what the model does. The analogy is not decoration. The web platform has already answered, under pressure from millions of applications, most of the questions an agent harness faces: how a page waits, fetches, cancels, talks to other pages, survives a reload, and is watched by a developer. When a need appears here, the first question is what the web's answer was. | The web | Affordance | |---|---| | A page: markup, state, event handlers | An app: TSX, `useState`, handlers on `` and `useEvent` | | Layout: CSS fits content to a viewport | Layout: token style sheets fit content to a context window | | A link or button the user can see and use | An affordance: an action attached to tokens that survived layout | | The event loop | One instance: ordered inputs, tasks, microtasks | | `fetch` | `model()` (a fetch of a view), `harness.machine.call`, `fetch` | | `AbortController` | `AbortController` | | `postMessage` between windows | `harness.send` between instances; `Runtime::inbox` from outside | | An iframe | ``: a child instance with its own state and journal | | A Service Worker answering `fetch` events | `affordance serve`: the event `request`, answered on the machine `client` | | DevTools: console, network panel, the protocol | `console`, the observer, `affordance host` | | Reload, session restore | The journal: replay rebuilds the instance exactly | ## Three owners Every feature belongs to one of three owners. Most disagreements about a design are really disagreements about which. 1. **The app** (TSX, including the libraries in `views/`). What the model sees, which tools exist, when the model is called, how history is kept and folded, what needs the user's permission. A website's product decisions. 2. **The engine** (the language, layout, the instance's event loop, effects, the journal). What every app needs and no app could build for itself: exact tokens, deterministic replay, cancellation that actually stops work. The browser. 3. **The deployment and its host program** (`affordance.yaml`, or a program embedding the runtime). Which model server, which machines, which credentials, what an agent is allowed to reach. The user's computer and network. A browser does not know what a shopping cart is. The engine does not know what a coding agent, a conversation, a permission prompt or a file is. ## The test for a new need 1. **Name the web's primitive for it.** If a web application would solve this with standard APIs, say which. 2. **Compose first.** Most needs are an arrangement of primitives that already exist. Write that arrangement. If it works, the feature is library TSX or deployment configuration, and the engine does not change. 3. **If something is truly missing, add the smallest general primitive**: nothing in it names a product, a vendor, a file or a process; it is useful beyond the case that prompted it; a replay reproduces it; it behaves under cancellation, pause and restore. 4. **Check the ordinary cases**: a chat bot, an autonomous tool-using agent, a fleet of agents, a resumed journal. If one needs a workaround, the primitive is wrong. ## Decisions, and why they went the way they did **Stopping a generation.** The need: the user presses Escape; stop now, and keep what was written. The tempting design is a harness call, `interrupt()`. The web's answer is `fetch(url, {signal})` with an `AbortController`, so `model()`, machine calls and `fetch` take a signal. Two details follow from taking the parallel seriously. An aborted `model()` *resolves* with the partial output instead of throwing, because the app is the reader of a stream and a stream's reader keeps the chunks it read. And whether a signal is aborted is kept by the instance, not in the controller object, because what an app keeps in state is frozen and must be reproducible from the journal. **Time and randomness.** A handler that read the wall clock would behave differently on replay. So `Date.now()` is the instance's clock, which advances only with journaled inputs, and `Math.random()` is refused with a message naming `harness.random()`. The rule behind both: everything a handler observes arrives as a journaled input. **`console.log`.** An app needs to say things to its developer. If those lines were state, they would change renders; if they were journaled, debugging would change the journal. A browser's console is neither: it is the DevTools view of a page. Here, console lines go to the instance's trace, which observers see, and nowhere else. **The loop is not the engine's.** The runtime never calls the model on its own. An autonomous agent (`useLoop`), a conversation (`useConversation`) and a chat driven by a frontend (`useFrontend`) are each a few dozen lines of library TSX over the same primitives, and an app can copy and change them. A browser has no opinion about when a page fetches. **Fitting the context window.** Dropping old history and eliding old tool results is layout, as `overflow` is in CSS: the engine does it, exactly, in tokens. Deciding to summarize, and what a summary says, is the app's: it listens for the layout event and makes an ordinary model call. **Serving HTTP.** The need: put an app behind an HTTP endpoint. The web's answer is a Service Worker's `fetch` event and `respondWith`. So a request is an event to the app, and the response is a call on a machine named `client`. Routing, JSON, and an OpenAI-compatible API are library TSX. The one thing that was missing was a way for a program outside to post an event into a running runtime; that became `Runtime::inbox`, which knows nothing about HTTP. **A frontend.** A terminal UI needs to drive an agent and watch it. The web's answer is the DevTools protocol: a second channel that sees the page without being the page. `affordance host` is that channel. A permission prompt was not added to it. Instead the frontend is a machine, `ui`, and an app that wants permission calls it and waits. Which actions need permission is therefore the app's decision, where a product decision belongs. **What the frontend is told.** A frontend wants to know when a tool starts, and to redraw a conversation after a restart. Both were first requested as protocol events. Both turned out to be compositions: the chat library tells the frontend the model's calls before it runs them, and answers the event `history` with its log. The protocol did not change. **File tools.** A coding agent wants `read`, `write` and `edit`. They are `views/tools/files.tsx`: library functions over a machine's shell. Nothing about them needed the engine, so the engine has no notion of a file. **A wait that watches a process.** A client wanted `wait` to end when a process on a guest machine exited. It was built into the engine, then removed: watching a guest is a property of that client's machines, not of waiting. The client composes it from a machine call and `harness.wait`. ## How to tell you are on the wrong side of the line - The engine change mentions a product noun: file, repository, permission, conversation, tool name, vendor. - The feature could be written in an app today, only less conveniently. Then it is a library. - A replay would not reproduce it, or would need the outside world to cooperate. - It makes one of the ordinary cases special. And the opposite error, rarer but real: an app is asked to do what only the engine can do honestly, such as counting tokens by estimate, cancelling work by ignoring its result, or remembering by re-reading the outside world. --- Source: spec/LANGUAGE.md Page: https://affordance.rs/docs/language.html # The view language Views are TypeScript/JSX files (`*.tsx`) implementing the JavaScript subset specified here. Intentional differences are in §7.3; unsupported features are in §7.4. Everything here is implemented in `src/` (`tsx.rs`, `parser.rs`, `interp.rs`, `jsvalue.rs`) and exercised by `views/`, including the conformance views that reproduce 740 models' official chat templates token for token. ## 1. What a view is A view is a program that turns **state** (a JSON object) into a **list of token ids** for one model's tokenizer, plus **spans** (labelled token ranges, affordances, token-budget boxes). It never builds the prompt as one string. Special tokens are emitted as ids; text is emitted in *runs* that are encoded with the model's tokenizer (section 6). ``` state (JSON) ──► view program ──► [ids] + [spans] ▲ bound to a tokenizer at load time ``` For chat templates the state is the object the official template gets: `messages`, `tools`, the kwargs (`add_generation_prompt`, `enable_thinking`, ...) and the tokenizer's special-token strings (`bos_token`, `eos_token`, ...). ## 2. Files The bound `tok` namespace is immutable from creation. Global `fetch`, `Headers` and buffered `Response` are supplied by the embedded Web API standard library. Fetch runs in effects/handlers through an explicitly bound HTTP executor; it grants no network access by itself. See `docs/HTTP_AND_MCP.md` for the supported Fetch subset, named capabilities and standard-library behavior. ```tsx "use strict_tokens"; // directives (6.3, 6.4) import { pythonTypeName } from "../common/checks.tsx"; // explicit file binding import "./chat.tss"; // a token style sheet (4.1) const NAME = expr; // evaluated once per render, before the root function name(a, b = 1, ...rest) { statements } const Turn = ({ role, children }) => p`${tok.im_start}${role}\n${children}${tok.im_end}\n`; export default function Main({ messages, tools }) { return <>...; } ``` The root is a function named by the caller (e.g. `Qwen3`); it receives the whole state as its props object. Declarations are private to their file; imports bind explicit exports (§2.1). TypeScript syntax is parsed and erased: annotations of any shape (object, union, tuple, function, conditional and template-literal types), optional parameters (`x?: T`), `type` and `interface` declarations (exported or not), type parameters on functions and arrows (`(x: T) => ..` in TSX), type arguments at calls (`useState([])`), `as` / `satisfies` casts and the non-null `x!`. Comments: `//`, `/* */`, and `{/* ... */}` in JSX. The Rust `View::render` API accepts arbitrary app state. `View::render_chat_opts` adds the Hugging Face chat wrapper's tool-schema validation and iterable-to-list conversion before rendering a chat view. Validation is outside the core language; an app may use a state field named `tools` for its own data. A JSON integer larger than 2^53 is a number (as in JavaScript) that keeps its exact decimal digits when printed; arbitrary-precision arithmetic is not implemented. ### 2.1 File modules ```tsx import MainView from "./main_view.tsx"; import { Tool, lookup as find } from "./tools.tsx"; import DefaultView, { helper } from "./views.tsx"; import "./setup.tsx"; // load/evaluate; introduces no names import type { Input } from "./types.tsx"; // erased; no runtime dependency export function Widget(props) { return ; } export { find as search }; export default function Main(props) { return ; } ``` Functions, constants and classes are private unless exported. Supported exports are `export function`, `export const`/`let`, `export class`, named default declarations and `export {local as public}` (including `as default`). A default export does not also create a named export. An entry selects a function declared in its root file, falling back to that file's default export when the requested declaration is absent. Relative paths resolve from the importing file; absolute paths are also accepted. A path that starts with `@affordance/` names a file of the library (`@affordance/lib/log.tsx`), as an import map names a package: the deployment's `library` directory, or the copy bundled with Affordance. Source files are `.tsx`, styles are `.tss`. Canonical file identity deduplicates a dependency in a program, including diamond imports. Constants initialize dependency first, in source order; a read of an uninitialized module constant throws a ReferenceError. Module constants are frozen as described in §7; modules do not provide mutable persistent state. Startup initialization still happens once per render. Declared functions keep compiled-declaration identity across renders for equality, Map/Set keys and effect dependencies, while retained functions execute against their defining initialization's lexical snapshot. Each runtime source load creates fresh declarations (§2.2). Named/default imports introduce only their listed local bindings. Export aliases preserve the identity of the referenced value. Functions, parameter defaults, closures, class methods and tool type-schema lookup resolve names in their defining file, including during effect replay. Imported JSX components and mounts resolve the same function; a mounted child's entry uses its declared function name. Render inputs, builtins and platform globals remain available unless shadowed by lexical bindings. Style sheets retain the global cascade described below. Duplicate declarations/import bindings/exports, missing exports and exports of undefined bindings are load errors. Cyclic imports, namespace imports (`import * as ...`), re-exports with `from`, dynamic imports and package resolution are unsupported and fail explicitly. Type-only imports are erased; cross-file type aliases are not available to `schemaOf`. The built-in module `affordance:web` exports `fetch`, `Headers`, `Response`, `createFetch`, `AbortController` and `AbortSignal`; its implementation's private names are inaccessible to apps. All but `createFetch` are also shadowable platform globals (abort signals: `spec/HARNESS.md` §3). `createFetch` selects an explicitly bound HTTP role; see [HTTP_AND_MCP.md](../docs/HTTP_AND_MCP.md). ### 2.2 Runtime source modules `loadModule(source, {imports?})` from `affordance:compiler` returns a frozen export namespace using the same parser and executor as file modules. `imports` maps exact import specifiers to objects containing named/default exports; installed `affordance:` modules resolve automatically. Loading performs no filesystem/network lookup. Each load creates a distinct lexical instance; functions, defaults, closures and type schemas retain it across later calls and awaits. ```tsx import {loadModule} from 'affordance:compiler'; // In a handler, then retain exports in state: const next = loadModule(source, {imports: {'./helpers.tsx': {format}}}); // In the parent component: // ``` Acquire source in recoverable app inputs and keep exports in state rather than loading on every render. A lazy state initializer may load initial source. Source parse/initialization errors are catchable before selecting a revision. The app owns revision history and controls; a new `key` resets child-local state, and undo selects old code with fresh local state after removal. Source is charged to execution fuel. Global fuel exhaustion aborts the render, including its parent; source modules share the instance's capabilities and computation allowance. Initialization is synchronous and pure for both file and source modules: no hooks, async calls, await, Promise reactions, host effects, interactive JSX, scroll viewports or mounts. Put those inside component/function bodies. Passive text/token constants and class definitions are valid. Initializers cannot see the loader caller's locals; documented app render inputs and platform globals remain available. Imported values are deep-frozen, including captured closure cells; module `let` is read-only just like file-module constants. Runtime modules use the bound tokenizer, parent styles and document policy. Style-file imports are unsupported; use inline styles or the parent's existing stylesheet. `strict_tokens` applies normally; `safe_text` must already be selected by the parent. Unknown directives/options and missing imports/exports fail explicitly. `js` remains a no-op. `` needs a file-backed entry; a file-backed wrapper can load source from its props to run a separate instance. See the [live-component example](../views/demo/live_components.tsx). ## 3. JSX and prompt text Components are functions that return a value; elements are values. Children follow React's rules: strings as text, numbers as JavaScript prints them, arrays spliced (each element is one item for a dropping box, 4.1), `true`/`false`/`null`/`undefined` render nothing, a plain object is an error. Component tags resolve function values: `` may use a local, prop or closure, and `` reads an object member. Intrinsic spellings (`Mount`, `tok.*` and the lowercase elements below) remain reserved. A missing or non-callable component is an error; a string value does not name an intrinsic element. Elements have structural paths. An explicit string/number `key` identifies a sibling; duplicate sibling keys are errors. Otherwise identity uses the JSX tag spelling and its evaluated sibling position among that tag. Arrays splice in order; null/false/undefined create no element. Hooks use that path and hook order. `id` and `label` select/describe presentation and do not reset hooks. Fresh function values at the same path preserve state; this is different from React's function-object identity. Removing a component discards its local state and cleans up its effects; named `useState(init, "name")` fields remain instance-wide. | syntax | meaning | |---|---| | `` p`text ${x} more` `` | a **prompt fragment**: literal text (split on special tokens at load time) and values in order | | `` `text ${x}` `` | a plain string (JavaScript template literal) | | `{expr}` in JSX | a child (rules above) | | `children` | call a function component with a props object (`children` is a fragment) | | ``, `${tok.im_start}` | one special token (6.4) | | ``, `` | a special token chosen at render time; a raw token id | | `..` | labelled span (token range is reported); extra props travel as meta | | `..` | an **affordance**: an action attached to the tokens of its children (section 5) | | `..` | token-budget box (section 4) | | `..` | a picture sized by layout (4.1): the tokens its model's processor gives it within `max-tokens`; the request carries the file at that size | | `` | `n` placeholder tokens for an image, the file as it is | | `