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)
// 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'
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 })
commit returns { ok: false, reason: 'build-error', errorText }; the session stays open.commit merges, see below.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.createBranch, branches, merge (fast-forward only), deleteBranch.build again.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 }
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.read shows the markers, a replace op swaps the whole block for merged code. Then commit again.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.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)
| Error | Where it shows | What the user sees |
Syntax error, missing import, bad @apply | build returns { ok: false, errorText }, no url | nothing changes; give errorText to the model |
| Module throws at top level | import(url) rejects in the browser | client keeps the previous module |
| Component throws in render or an effect | React error boundary in the browser | client keeps the previous module |
/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./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.| Path | Content |
malleable.json | { "entry": "App.tsx", "externalPackages": ["react", ...] } |
| source files | whatever the agent writes; dist/ and .git/ paths are rejected |
dist/index.js, dist/chunks/*, dist/index.css | build output, written by the DO on commit |
await project.dependencies() // { 'date-fns': '4.4.0', zustand: '5.0.15' } await project.updateDependencies({ names: ['date-fns'] }) // next build takes the latest again
'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.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 }) ◀┘
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} /> ))}
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./api/projects/* needs Authorization: Bearer $MALLEABLE_API_KEY. /p/* and /view/* are public by project id, including the WebSocket. Use unguessable ids.| Route | Method | Purpose |
/api/projects/:id | POST, GET | init, info |
/api/projects/:id/sessions | POST, GET | open, list |
/api/projects/:id/sessions/:sid/ops | POST | { ops: [{ op: 'write' | 'replace' | 'delete', ... }] }, atomic |
/api/projects/:id/sessions/:sid/{files,file?path=,diff?from=,status} | GET | list, read, uncommitted diff, conflicts |
/api/projects/:id/sessions/:sid/{build,commit} | POST | draft build, commit |
/api/projects/:id/sessions/:sid | DELETE | discard |
/api/projects/:id/diff?to=&from= | GET | diff of a commit or between two refs |
/api/projects/:id/{log,files,undo,restore,branches,merge} | history and branches | |
/p/:id/r/:ref/* | GET | built file at a branch or sha |
/p/:id/d/:sid/:build/* | GET | draft build file |
/p/:id/live | WS | hello, update (kind: 'draft' | 'commit'), build-error, conflict, draft-end |
/view/:id | GET | minimal live viewer page |
/api/projects/:id/git-tokens | POST, GET | create a git token (secret shown once), list tokens |
/api/projects/:id/git-tokens/:tokenId | DELETE | revoke a git token |
/git/:id.git/* | GET, POST | git smart HTTP proxy |
// 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
log() maps any author email that is not agent@ or system@ to { kind: 'user', id: <git name> }.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.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.commit merges with it.build-error with session: 'git-push', and the head keeps its old dist/./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
@malleable/ui (source in src/client.ts) wraps every REST route and the socket. demo/App.tsx and examples/*.ts are the reference use.| Class | Methods |
Project | init, info, openSession, sessions, log, diff, files, undo, restore, branches, createBranch, merge, deleteBranch, createGitToken, gitTokens, revokeGitToken, watch |
Session | apply, read, list, diff, status, build, commit, discard |
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) } }, })
apply({ ops }).| Message | When | Fields |
hello | on connect | heads, drafts[] (each has url, session, branch, build, stats) |
update kind: 'draft' | build | url, session, branch, build, stats (vs session base). Not in git, lost on DO restart |
update kind: 'commit' | commit, undo, restore, merge, git push | url, branch, sha, message, author, stats (vs previous head). Immutable url |
build-error | build failed | session (git-push for pushes), errors |
conflict | commit hit overlapping edits | session, conflicts |
draft-end | session committed or discarded | session, outcome |
url is relative to the Worker origin, so clients never build /r/ or /d/ paths themselves.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.base commit (read through the Artifacts binding) plus its op log. A merge compacts the op log to writes against the new base.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.gitHttp in project-do.ts: it keeps the 5xx response body.