Packages
The surface package
Experimental. Server mode: createSurface in Node. Client mode: the same createSurface, loaded in the browser from @culmjs/surface/client. Either way the browser runs mountSurface. Proved only in Chromium.
A surface is a one-page Culm document that a product draws in part of its own page. surfaces.md is the behaviour reference: the profile, the operations, the refusals, the patch and the mount.
Set up
Nothing is on npm yet. In a checkout of this repository run npm run pack:all, which writes the tarballs to .pack/. Install .pack/culmjs-surface-0.0.0.tgz. @culmjs/core is a peer dependency: install .pack/culmjs-core-0.0.0.tgz too. Node 22.18 or later.
Entry
Where
What it holds
Entry
@culmjs/surface
Where
Node
What it holds
createSurface, describeSurface, DESCRIBE_VERSION, ORDER_RULES, and the types Changed, Surface, SurfaceOptions, Content, Patch, PatchElement, SurfaceEvent, LineResult, StreamStep and SurfaceStream
Entry
@culmjs/surface/mount
Where
Browser
What it holds
One ES module. Its only runtime export is mountSurface. Types: MountOptions, SurfaceView
Entry
@culmjs/surface/client
Where
Browser
What it holds
One self-contained ES module exporting createSurface, createRegistry and API_VERSION
Entry
@culmjs/surface/mcp-apps
Where
Node
What it holds
mcpAppsResource, mcpAppsActionTool and MCP_APPS_ACTION_TOOL: a surface served as an MCP Apps view. See generative-ui.md
Server mode
import { readFileSync } from 'node:fs'
import { createRegistry } from '@culmjs/core'
import { createSurface } from '@culmjs/surface'
const registry = createRegistry()
const profile = {
kinds: ['column', 'text'],
blocks: [],
layout: 'desktop' as const,
elements: 40,
depth: 6,
}
// `look` is a Culm site's `look`, from its site.json
const look = JSON.parse(readFileSync('site.json', 'utf8')).look
const made = createSurface({ registry, profile, look })
if (!made.ok) throw new Error(made.problems[0].message)
const { surface } = made
const result = surface.apply([
{
op: 'add',
tree: surface.page.tree,
parent: surface.page.root,
index: 0,
node: { kind: 'text', props: { runs: [{ text: 'Hello' }] } }, },
])
if (result.ok) {
// send result.patch to the browser
} else {
// result.problems says what was refused; nothing changed
}createSurface, apply and setData are synchronous and return problems. They never throw.
Options of createSurface:
registry: the registry the document is checked and drawn with.
profile: { kinds, blocks, layout, elements, depth }. See the profile.
look: a Culm site's look. Give either look or document.
document: a saved SiteDocument, instead of look.
revision: the saved document's revision. Only with document.
data: the rows for lists and other sources.
links: the Links that turn a file id into an address.
icons: the site's icons.
fonts: the site's fonts.
fontBase: the address that font files load from.
apply(ops, { baseRevision, key }) takes a batch of operations. Both options are optional.
baseRevision makes the batch fail with REVISION_CONFLICT if the surface is at another revision.
key makes a retry safe. The same key with the same request returns the first result again. The same key with other content is KEY_CONFLICT. Only the latest key is remembered.
setData(data) replaces all the rows. setData({ rows: {} }) clears them. A call made while a change is being drawn (from code of yours that the drawing calls) is refused.
In the browser
import { mountSurface } from '@culmjs/surface/mount'
const view = mountSurface(el, {
onAction: event => send(event), // your transport, to your server
})How a patch gets from the server to view.patch is the product's own transport. Send each patch from apply or setData to view.patch.
If view.patch returns false, a patch was missed. Fetch surface.snapshot() on the server and pass that.
view.patch throws on a refused or malformed patch (the message starts "The patch "), and after view.destroy() ("View destroyed."). Catch it.
onAction events are submit, press and goTo. Send them to the server and check every value there. The mount reports what the person did and trusts none of it.
Behaviour of the patch and the mount: the patch, the mount.
Client mode
Load the module when it is first needed (the path is wherever your product serves client.js):
const { createSurface, createRegistry } =
await import('/assets/culm-surface/client.js')Then make the surface with the same calls as in server mode, and send each patch to view.patch as above.
Use the createRegistry this module exports, not a second copy of @culmjs/core.
The module is large (limits.md), so load it only when needed.
It contains no eval, so it runs under a policy without 'unsafe-eval'.
Values from onAction must still be checked by your server.
Package pieces
createSurface({ ..., pieces }) takes the components of an approved package the product offers, and profile.pieces names (by component id) the ones this surface may hold. The agent may place an instance of one and set its settings, never edit its tree. A piece with an island is refused. Pass the same pieces again on restore. See surfaces.md. The client bundle is 129,137 B Brotli with this (ceiling 135,000).
Streaming
A model can write operations one per line. surface.stream() checks and applies each line as it arrives, in both modes. The rules are in generative-ui.md.
import { describeSurface } from '@culmjs/surface' // Node entry only
const described = describeSurface(registry, profile)
if (!described.ok) throw new Error(described.problems[0].message)
// give described.text to your model; its reply goes into the stream
const stream = surface.stream()
for await (const chunk of reply) {
const step = stream.write(chunk) // text only: decode bytes first
send(step.patches) // to the browser, in order
// step.lines: one entry per line, { line, ok, op } or { line, ok: false, problems }
}
stream.close()surface.stream({ spelling: 'outline' }) reads an indented outline instead, one line per node, with the same checks and ceilings; give the model describeSurface(registry, profile, { spelling: 'outline' }).text. A section is applied one line late. The outline is in the Node entry only; in client mode stream({ spelling: 'outline' }) throws a TypeError. See the outline spelling.
In the browser, queue the patches and apply them in one animation frame. view.patch stays synchronous; the frame only groups the work:
const queue = []
let waiting = false
let asked = false
function receive(patches) {
queue.push(...patches)
if (waiting) return
waiting = true
requestAnimationFrame(() => {
waiting = false
for (const patch of queue.splice(0))
if (view.patch(patch)) asked = false
else if (!asked) {
// the mount missed a patch: ask the server once for surface.snapshot(), and pass it to receive()
asked = true
askForSnapshot()
}
})
}Every view.patch in the drain should return true. A false means a patch was missed. Every later patch of the stream then returns false too, so keep draining and ask once for surface.snapshot(): a snapshot is a full state, which the mount applies, and it arrives in the queue behind those patches. Browsers pause requestAnimationFrame in hidden tabs and frames, so a hidden view keeps its patches in the queue until it is shown.
To restore a surface, use surface.snapshot() or surface.state(), not a replay of its stream.
Saving and restoring
Save surface.state(), which is { document, revision }. Rows are not in it.
Restore with createSurface({ ...sameOptions, document, revision, data }). Leave id out. The restored surface takes a new id and its v starts again at 1. The mount applies a full state from a new id and keeps typed text.
Only the latest request key is remembered, and none survives a restart. A retry across a restart needs baseRevision.
A client-mode state() comes from the browser, so the person can change it. If a server restores it, a required: true node the person removed stays gone, because the check compares against the document you hand in. Keep the saved document on the server, or check it before restoring.
The page policy
If your page's policy blocks style attributes, add style-src-attr 'unsafe-inline'. The compiled surface writes style attributes (background images, shapes), and the spike found a style attribute set by script blocked under style-src 'self'. The spike did not run under a policy that blocks style attributes. The client-mode browser tests ran under default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self'; font-src 'self', which allows them. Those tests set font-src 'self' but did not assert that a font loads, so font loading under a restrictive font-src is not tested.
Files load only from what links.file returns, and fonts only from fontBase, so the policy must allow those addresses.
Limits
A plug-in kind whose tag() returns a tag outside the mount's lists makes view.patch throw on a patch createSurface accepted. Register only plug-in kinds whose tags and attributes are on those lists: TAGS, ATTRS and data-s-* in packages/surface/src/mountHost.ts.
Compiling is synchronous and blocks the server's event loop (in client mode, the page's main thread). Limit how many surfaces a server runs at once.
State lives in one process. Keep one instance per surface, or restore from state().
Not built for a surface inside a Culm-built page or a frame, except the MCP Apps view (@culmjs/surface/mcp-apps).
Ceilings and measured figures: limits.md. What the browser cannot stop: surfaces.md. What was not tested: surfaces.md.
Previous