Agent-readable docs index: /llms.txt. Full docs in one file: /llms-full.txt. Download /docs.zip to grep all markdown files locally.

Projects API: sessions, drafts, commits and git

Projects

A project is a git repo in Cloudflare Artifacts plus a Durable Object (ProjectDO) that is its only writer.
agent (Worker) ──RPC──▶ ProjectDO ──git push──▶ Artifacts repo (src files + dist/ in one commit) agent (HTTP) ──REST──▶ │ rollup + tailwind run here └──WebSocket──▶ viewers: draft / update messages browser ◀── import() ── GET /p/:id/r/:sha/index.js (immutable) or /d/:session/:n/index.js (draft)

Setup

// website/wrangler.jsonc (needs wrangler >= 4.145; Artifacts is in beta) { "compatibility_date": "2026-09-01", "artifacts": [{ "binding": "ARTIFACTS", "namespace": "lovepack" }], "kv_namespaces": [{ "binding": "jsCache", "id": "<kv id>" }], // build cache "vars": { "PUBLIC_URL": "https://malleableui.dev" }, // origin used in git remote urls "durable_objects": { "bindings": [{ "class_name": "ProjectDO", "name": "PROJECT" }] }, "migrations": [{ "tag": "v3", "new_sqlite_classes": ["ProjectDO"] }] }
wrangler secret put MALLEABLE_API_KEY # REST auth
// website/src/app.tsx: the class must be exported from the Worker entry export { ProjectDO } from './project-do.ts'

Flow

const project = env.PROJECT.get(env.PROJECT.idFromName('u123')) // Durable Object stub, RPC await project.init({ projectId: 'u123' }) // idempotent; { template } forks a repo const { sessionId } = await project.openSession({ author: { kind: 'agent', id: 'ses_1' } }) await project.apply({ // atomic, in memory, logged in DO SQLite sessionId, ops: [ { op: 'write', path: 'App.tsx', content: code }, { op: 'replace', path: 'Card.tsx', oldString, newString }, // throws unless `oldString` occurs once ], }) await project.build({ sessionId }) // draft: viewers update, nothing is committed await project.commit({ sessionId, message: 'Add chart' }) // build + git add . + commit + push // or project.discard({ sessionId })
  • Many sessions per branch. Agents work in parallel, each on its own tree. A session idle for 24 hours is discarded.
  • Failed builds do not commit. commit returns { ok: false, reason: 'build-error', errorText }; the session stays open.
  • Head moved since open: commit merges, see below.
  • History: log (each entry has the url of its build), diff, undo (new commit with the previous sources), restore({ sha }) (new commit with the sources of any commit, also a later one; noop when nothing changes). History is never rewritten.
  • Branches: createBranch, branches, merge (fast-forward only), deleteBranch.
  • Drafts live in DO memory only. The last 3 builds per session are kept. A DO restart loses them; call build again.

Parallel sessions and conflicts

commit is optimistic. If nothing landed since the session opened, it builds and pushes. Otherwise it three-way merges the session onto the new head first:
agent A ─ commit ──────────────▶ main: A agent B ─ commit ─▶ merge(base, main, B) ─ clean ──▶ main: A + B { ok: true, merged: true } agent C ─ commit ─▶ merge(base, main, C) ─ overlap ─▶ markers in C's files { ok: false, reason: 'conflict', conflicts, prompt }
  • Files changed on one side take that side. Files changed on both are merged line by line.
  • On a conflict the session moves onto the new head and its files contain diff3 markers. Nothing is committed.
  • prompt tells the agent which commits landed (message and author), which lines conflict and how to fix them. Give it to the model as is.
  • The agent resolves with its normal tools: read shows the markers, a replace op swaps the whole block for merged code. Then commit again.
  • Markers are the only conflict state. build and commit refuse a tree with <<<<<<< lines; session.status() lists them.
<<<<<<< yours (session s_1) <p className="text-sm">Totals per month</p> ||||||| base <p className="text-sm">Monthly totals</p> ======= <p className="text-sm">Weekly totals</p> >>>>>>> main a1b2c3d
examples/parallel-agents.ts runs the whole flow. With one agent at a time nothing changes: the head has not moved, so commit skips the merge.

Stream component urls in the chat response

build, commit, undo, restore and merge return the url of the new entry module, relative to the Worker origin. An agent loop in a Worker can send it to the user in the same stream as its tokens. The client needs no watch.
browser ──POST /chat──▶ agent Worker ──RPC──▶ ProjectDO ▲ │ tool call: apply + build ──▶ { ok, url: '/p/u123/d/s_1/2/index.js' } └── SSE: tokens, ui-url ◀┘
// agent Worker, inside a tool of the AI chat const result = await project.build({ sessionId }) if (result.ok) writer.write({ type: 'data-ui', data: { url: result.url } }) // same SSE stream as tokens else return result.errorText // let the model fix the code // browser const mod = await import(new URL(part.data.url, MALLEABLE_ORIGIN).href) setComponent(() => mod.default)

Errors

ErrorWhere it showsWhat the user sees
Syntax error, missing import, bad @applybuild returns { ok: false, errorText }, no urlnothing changes; give errorText to the model
Module throws at top levelimport(url) rejects in the browserclient keeps the previous module
Component throws in render or an effectReact error boundary in the browserclient keeps the previous module
The server cannot run the component, so runtime errors are only caught in the browser. /view/:id (website/src/view-page.ts) and demo/App.tsx show the pattern: render each module in an error boundary keyed by its url, and keep the last module that did not throw as the fallback. Errors in event handlers and async code are not caught by error boundaries.
Commit urls (/p/:id/r/<sha>/index.js) are immutable, so store them in chat history. Draft urls stop working after a DO restart or after 3 newer builds; reload them from the commit.

Repo layout

PathContent
malleable.json{ "entry": "App.tsx", "externalPackages": ["react", ...] }
source fileswhatever the agent writes; dist/ and .git/ paths are rejected
dist/index.js, dist/chunks/*, dist/index.cssbuild output, written by the DO on commit
The entry module default-exports the component. Its CSS is loaded relative to the module URL. npm packages are not bundled: they are imports of esm.sh urls with exact versions, so a commit sha URL never changes, but it needs esm.sh at runtime.

npm versions

The first build that imports a package locks its latest version in the project. Later builds, in every session, use the locked version and send no request for it.
await project.dependencies() // { 'date-fns': '4.4.0', zustand: '5.0.15' } await project.updateDependencies({ names: ['date-fns'] }) // next build takes the latest again
An import with a version ('date-fns@3') skips the lock. A package or subpath that does not exist fails the build. A missing named export does not: the browser reports it when it imports the module.

Diffs

One method, both full versions of every changed source file. dist/ is never in a diff.
await project.diff({ to: sha }) // one commit vs its first parent (one agent message) await project.diff({ from: 'main', to: 'exp' }) // any two branches or shas await session.diff() // uncommitted changes vs the session base await session.diff({ from: firstSha }) // uncommitted changes vs any commit // => { from, to, stats: { files, additions, deletions }, files: DiffFile[] }
build, commit and every live update carry stats, so a +12 −3 badge needs no request. Fetch the diff only when the user opens it.
build() ─▶ { url, stats } commit() ─▶ { sha, parent, url, stats } live update ─▶ { ..., stats } │ click project.diff({ to: sha }) ◀┘
Each DiffFile has oldFile and newFile as { name, contents }. Full contents, not a patch, so the viewer can expand unchanged lines. Render them with featherdiff:
import { FileDiff } from 'featherdiff' {diff.files.map((f) => ( <FileDiff key={f.path} path={f.path} oldText={f.oldFile?.contents ?? null} newText={f.newFile?.contents ?? null} /> ))}
A first commit diffs against the empty tree (from: null). A session diff has to: null. Line counts come from an LCS line diff, the same as git diff --stat in most cases.

REST

/api/projects/* needs Authorization: Bearer $MALLEABLE_API_KEY. /p/* and /view/* are public by project id, including the WebSocket. Use unguessable ids.
RouteMethodPurpose
/api/projects/:idPOST, GETinit, info
/api/projects/:id/sessionsPOST, GETopen, list
/api/projects/:id/sessions/:sid/opsPOST{ ops: [{ op: 'write' | 'replace' | 'delete', ... }] }, atomic
/api/projects/:id/sessions/:sid/{files,file?path=,diff?from=,status}GETlist, read, uncommitted diff, conflicts
/api/projects/:id/sessions/:sid/{build,commit}POSTdraft build, commit
/api/projects/:id/sessions/:sidDELETEdiscard
/api/projects/:id/diff?to=&from=GETdiff of a commit or between two refs
/api/projects/:id/{log,files,undo,restore,branches,merge}history and branches
/p/:id/r/:ref/*GETbuilt file at a branch or sha
/p/:id/d/:sid/:build/*GETdraft build file
/p/:id/liveWShello, update (kind: 'draft' | 'commit'), build-error, conflict, draft-end
/view/:idGETminimal live viewer page
/api/projects/:id/git-tokensPOST, GETcreate a git token (secret shown once), list tokens
/api/projects/:id/git-tokens/:tokenIdDELETErevoke a git token
/git/:id.git/*GET, POSTgit smart HTTP proxy

Git remote

Users can edit with plain git. The Worker proxies Artifacts' git remote and checks its own tokens, so Artifacts credentials never leave the Worker.
// REST client (API key) or DO RPC from a Worker: same arguments, same result. // scope read|write (default write); ttl in seconds, omit it for a token that never expires const { id, authenticatedUrl } = await project.createGitToken({ label: 'laptop' }) // => { id, token, url, authenticatedUrl, username, scope, label, createdAt, expiresAt, lastUsedAt } await project.gitTokens() // list, with lastUsedAt; secrets are never returned again await project.revokeGitToken({ id }) // the next git request with it gets 401
git clone "$AUTHENTICATED_URL" app && cd app # edit App.tsx git commit -am 'Tweak' && git push origin main
  • Pushed commits are by users. log() maps any author email that is not agent@ or system@ to { kind: 'user', id: <git name> }.
  • After a push, ProjectDO.afterGitPush() builds the pushed sources. If dist/ does not match, it adds a commit Build dist for pushed sources, and viewers get an update. Run git pull to get it.
  • Tokens (lpgit_<48 hex>) live in the project DO (GitTokenStore in website/src/project-store.ts). Only their SHA-256 is stored. Every git request asks the DO to verify the token, so revocation is immediate.
  • Push while an agent session is open is allowed. The session's next commit merges with it.
  • A push with a build error still lands, viewers get build-error with session: 'git-push', and the head keeps its old dist/.

Example

/view/:id is a minimal live viewer. examples/agent.ts plays an agent (two messages, one commit each):
MALLEABLE_API_KEY=... pnpm tsx examples/agent.ts demo1 # then open $ORIGIN/view/demo1

Client

@malleable/ui (source in src/client.ts) wraps every REST route and the socket. demo/App.tsx and examples/*.ts are the reference use.
ClassMethods
Projectinit, info, openSession, sessions, log, diff, files, undo, restore, branches, createBranch, merge, deleteBranch, createGitToken, gitTokens, revokeGitToken, watch
Sessionapply, read, list, diff, status, build, commit, discard
Failed calls throw MalleableError with status and code (for example SESSION_NOT_FOUND, REPLACE_AMBIGUOUS). Responses are plain JSON.
// endpoint defaults to https://malleableui.dev; pass yours when you self-host const project = new Project({ endpoint, apiKey, id: 'u123' }) project.watch({ onMessage: async (msg) => { // draft or commit, every update has its own module url if (msg.type === 'update') { const mod = await import(msg.url) setComponent(() => mod.default) } }, })
All methods take a single object argument, in the RPC, the client and the REST bodies. Edits go through one method, apply({ ops }).

Live messages

MessageWhenFields
helloon connectheads, drafts[] (each has url, session, branch, build, stats)
update kind: 'draft'buildurl, session, branch, build, stats (vs session base). Not in git, lost on DO restart
update kind: 'commit'commit, undo, restore, merge, git pushurl, branch, sha, message, author, stats (vs previous head). Immutable url
build-errorbuild failedsession (git-push for pushes), errors
conflictcommit hit overlapping editssession, conflicts
draft-endsession committed or discardedsession, outcome
url is relative to the Worker origin, so clients never build /r/ or /d/ paths themselves.

Learnings

  • Artifacts has no file-write API. Writes are git push with isomorphic-git on an in-memory fs (website/src/memory-fs.ts).
  • isomorphic-git needs readlink and symlink on the fs, and err.code on fs errors.
  • git.commit({ ref }) needs the full ref (refs/heads/main). A short name writes a stray ref and the push fails with a bare 500.
  • git.fetch needs the origin remote configured (addRemote) and returns the fetched sha in fetchHead.
  • The DO keeps the clone in memory only. After hibernation a session tree is rebuilt from its base commit (read through the Artifacts binding) plus its op log. A merge compacts the op log to writes against the new base.
  • All DO state goes through ProjectStore (website/src/project-store.ts). It writes SQLite/KV first, then its in-memory cache, and loads caches lazily, so a fresh instance after hibernation reads storage. ProjectDO never touches ctx.storage.
  • Debug failed pushes through gitHttp in project-do.ts: it keeps the 5xx response body.