# Create a Robutler app

You're an AI coding agent helping someone **create a new Robutler app**: a small, self-contained web app (an HTML/JS/CSS bundle) that runs sandboxed in an iframe on the Robutler canvas. (You fetched this file from a Robutler host; everywhere below, **"this host"** means that same origin.)

**Read §2 before you write a single file.** Robutler is a remix platform. A new app written from a blank file is almost always the wrong first move, and it is the most common mistake agents make here.

## 1. Connect the Robutler MCP server

The portal exposes a Model Context Protocol server with the tools to browse, read, edit, and publish apps.

- **URL:** `/mcp` on this host (e.g. `https://robutler.ai/mcp`), Streamable HTTP transport.
- **Auth:** OAuth. Your environment opens a browser to authorize. There is **no API key to paste**.

| Environment | How to connect |
|---|---|
| **Claude Code** | `claude mcp add robutler --transport http https://<this-host>/mcp` then run `/mcp` to authorize |
| **Cursor** | Settings → MCP → Add → URL `https://<this-host>/mcp`, then authorize |
| **Codex** | Add `[mcp_servers.robutler]` (URL transport) to `~/.codex/config.toml`, then authorize |
| **Antigravity** | Settings → MCP servers → Add `https://<this-host>/mcp`, then authorize |

## 2. Survey what already exists (do this first, every time)

Nothing here is built in a vacuum. Every app on this host is source-available and readable through the same tools you are about to use, so the fastest correct implementation is usually one that already exists. Run this survey before scaffolding anything:

1. **List what is installed.** `widget_catalog()` returns every app available to this account with its `refId`, whether it is collaborative, and the document mimes it opens. Narrow it: `widget_catalog({ query: "sheet" })`.
2. **Search the wider marketplace.** The `search` tool (type `posts`) and `posts_read` reach published apps beyond the installed set.
3. **Read the closest two or three, in full.** `widget_download(<folderId>)` lists every file in a bundle and returns text inline up to a byte budget (default 200 KB); files past it come back with `omitted: true`, so call again with `paths: [...]` for the ones you need. Read its **`AGENT.md`** or `README.md` first: most apps ship a maintainer's guide with the architecture, the invariants, and "how to add X" recipes. Then read `widget.json` and the entry HTML. Every first-party app is also plain readable source at `<this-host>/widgets/<name>/`.
4. **Decide, and tell the user what you found.** One or two lines, before you build:
   - **An existing app already does this.** Say so and stop. Instantiate it with `widget_instantiate` instead of shipping a duplicate.
   - **One is close.** **Remix it**: `widget_remix(<refId>)` clones it into your own private, editable copy (any app you can use — published, or shared with you; a `via: <documentId>` argument covers an app that reached you as a shared document). Then follow `/REMIX.md`. You inherit a working structure, its test suite, its collab wiring, and its lineage, and the original author keeps attribution. **This is the preferred path and you should reach for it aggressively.**
   - **Nothing is close.** Scaffold new (§3), but carry over the patterns from what you just read rather than inventing your own.

A survey you did not report did not happen. State which apps you looked at and why you are building new.

### The shared library: never re-implement these

Reusable modules live at `/widgets/shared/` on this host and are importable by **absolute** URL (`/widgets/shared/<file>?v=N`). Read the module's header comment before using it.

| Module | What it gives you |
|---|---|
| `collab-kit.js` + `collab-kit.css`, `collab-boot.js`, `collab-offline.js`, `collab-readonly.js` | The proven multiplayer/document stack: topbar, presence, comments, save/open, offline. Any document-shaped app should build on this rather than wiring Yjs by hand. |
| `arcade-net.js` | Code-lobby netcode for realtime games, with a solo fallback when there is no room. |
| `arcade-score.js` | App-scope leaderboards over the shared `submit-score` / `leaderboard-top` functions. |
| `arcade-fx.js`, `arcade-maps.js`, `arcade-tools/` | Game effects, map handling, authoring tools. |
| `webrtc-mesh.js` | Opt-in voice/video/screen mesh over an existing `host.collab` provider (TURN creds included). |
| `docs-kit/`, `vector/`, `video/` | Document, vector and video editing primitives behind the shipped Docs, Vector and Video apps. |
| `print-kit.js` | Printing and PDF from a sandboxed mount (routes through `host.print`). |
| `fonts.js` | Google/Fontsource loading with buffers kept for exporters. |
| `geometry.js` | Alignment, distribution, smart-snap. Dependency-free and unit-tested. |
| `exchange.js` | The ADR-0028 envelope for moving a fragment of one app's document into another with provenance. |
| `splash.js` | The shared first-run feature card used by the creative apps. |
| `audio-viz.js`, `voice-*.js`, `viseme-utils.js` | Spectrum rendering, voice UI, visemes. |
| `test-kit.mjs` | Zero-dependency test helpers for the widget test standard (§5). Dual-runnable under node and in the iframe harness. |

### The reference apps

Four shipped bundles are the house style. Fetch any of them at `<this-host>/widgets/<name>/` or read them with `widget_download`:

- **`collab-board`**: the canonical collaborative app (Yjs, presence, comments, project documents).
- **`docs`**: a rich document editor with a server-side render pipeline.
- **`vector-editor`**: a heavy creative app: tools, layers, export.
- **`tank-arena`**: a realtime multiplayer game (netcode, lobbies, leaderboards).

When your app resembles one of these, copy its shape. Divergence should be a decision you can justify, not an accident.

## 3. Scaffold

Only after §2. **`create_widget(name, template?)` is the one-call path** (prefer it): it scaffolds the template, lands it as an editable bundle folder you own, registers it as a private widget, and mints a dev token. It returns two ids that split all later work — **`widgetContentId` mounts** the app (`widget_instantiate`), **`folderId` addresses its files** (`widget_put_files` / `widget_download`). `widget_scaffold(name, template?)` returns the same files map without writing anything server-side, if you want to iterate locally first. Templates:

- **`collab-app`** (default): a complete best-practice starter: Yjs realtime sync and presence, an agent command surface, `host.kv` prefs, a `host.fn` server function, a versioned project document, plus `AGENT.md`, README and tests. Start here unless you have a reason not to.
- **`minimal`**: a three-file hello world.
- **`webgpu`** / **`webrtc`**: add an opt-in GPU canvas or a peer video mesh.

Read the scaffold's own `AGENT.md` before editing it: it states the invariants (standalone must never break, commands stay in sync with the manifest, `serialize()` is pure data, mutations go through one path, server compute is the owner's money).

## 4. Build

Edit files with `widget_put_files(folderId, [{ path, text }])`. Keep the app self-contained: bundle or CDN-load dependencies, and don't assume a build step.

The app talks to the platform through the global `host` object (the SDK at `/widgets/sdk.v2.js`). Core surface: `host.ready()` (await before use), `host.kv` (per-INSTANCE prefs, small JSON), `host.fn` (your own server functions), `host.content` (project-folder file storage), `host.collab` (Yjs rooms), `host.commands.handle(name, fn)`, plus `host.live`, `host.user`, `host.discover`. The authoritative surface is the typedefs at **`/widgets/sdk.v2.d.ts`**; prose at **`/develop/sdk-v2`** and per-namespace guides under `/develop/` (`host-kv`, `host-content`, `host-fn`, `host-collab`, `host-live`, `host-user`).

**Exposing an agent command:** the agent control surface is the allowlist declared in `index.html`'s `<meta name="robutler:widget">` `interface.commands`. Registering a handler at runtime (`host.commands.handle('foo', fn)`) is NOT enough: if `foo` is not in the meta, an agent calling it gets `unknown_op`. **Footgun:** that meta's `content='…'` is parsed with a tolerant regex, so a single apostrophe (`'`) or a `>` (e.g. in `->`) anywhere inside the JSON silently truncates it and drops your commands. Use `→` instead of `->`, avoid apostrophes, and re-check the command list after editing.

**Who can call a server function:** each `widget.json` tool's `httpAuth` is `session` (the app's owner only), `visitor_session` (any signed-in person) or `public` (anyone; a missing value means `public`). Anything that reads or changes the owner's private data, or uses the owner's keys, secrets or connected accounts, is `session`. A function with `expose: ["tool"]` is also a tool on the app's agent with no scope of its own, so any caller that agent's run lets in can trigger it.

**Safari gotcha: load the entry module by absolute URL.** Your bundle runs in a sandboxed `srcdoc` iframe with an injected `<base href>`. Chrome honors that base for relative module specifiers; Safari does not, so `import('./app.js')` from the inline boot script fails there with *"does not resolve to a valid URL"*. Resolve against `document.baseURI`:

    const app = await import(new URL('./app.js', document.baseURI).href);

Only the first hop matters. Static imports inside `app.js` resolve against its own absolute URL.

## 5. Test before you publish

Ship the widget test standard: a `tests/` folder with `manifest.json` + `runner.html`, built on `/widgets/shared/test-kit.mjs`. If you remixed, the suite came with the bundle and **must be green before you publish**. Three equivalent ways to run it, all at the edge:

- call the app's own `runTests()` command → a JSON report `{pass, fail, results}`;
- open `<bundle>/tests/runner.html` in a preview and read `window.__testReport`;
- locally: `node scripts/test-widgets.mjs <widget>`.

Do not offer to publish while the suite is red. Surface the report to the user.

## 6. Mount, verify, publish

`widget_instantiate(refId=<widgetContentId>)` mounts the app on a canvas and returns a `canvasUrl` to open. **Verify the mount, never just the tool result:** the response's `mountKind` must be `"widget"` (a `"document"`/file mount means you passed the wrong id), `workspace_widgets_list` must list it, and `workspace_widgets_logs` must reach `loadState: "ready"`. After edits, `workspace_widgets_invoke(<itemId>, "__reload")` picks them up (bump any `?v=` tokens on assets you changed); `__screenshot` shows the pixels, and `widget_fn_logs` reads server-side function errors.

On accounts with publishing enabled, `widget_publish(<folderId>)` deploys to the public catalog and `widget_snapshot` cuts an immutable release. `app_status(appId)` shows the draft and the release of an app kept as project files, and `app_release_request(appId)` asks the owner to release its draft (it releases nothing itself; a later change to stored data ships with a release hook, `lifecycle.dataVersion` and `lifecycle.migrate` in `widget.json`, see `/develop/release-hooks`). From a terminal, the `robutler` command line does the same: `npm install -g robutler`, `robutler login`, `robutler app create`, `push`, `status`, `release`. Without those tools your app is private to your library — it still runs, mounts, and can be shared. Note: `widget.json` and the `<meta robutler:widget>` command surface are snapshotted onto the widget when it is created and refresh on republish, so declare the full command surface before you register/publish rather than patching it afterwards.

## 7. Where shared content lives (read before storing ANYTHING)

A document is often open in **two instances at once** (a second tab, a collaborator, a split view). For every byte you persist, ask: *will the other instance see it?*

- **Document body / structured state** → the **collab room** (Yjs via `host.collab`). Text, shapes, slides, rows, tool state.
- **Binary media** (images, figures, audio, exports) → **`host.content.put(file, { name })`**, which writes into the open PROJECT FOLDER (ADR-0022). Shared across instances and collaborators, travels with the doc. Reference as `content://<name>`, resolve with `host.content.get(name)`.
- **Binding**: `host.content` is project-scoped only once bound. Save binds automatically; a bespoke **open** flow must call `host.documents.bind(<folderId>)` itself or media 404s in the second instance.
- **Server-side state a viewer must not forge** (leaderboards, roll-ups) → your `widget.json` tools get `ctx.kv.at(scope)`: `'app'` is shared across every instance of your app type, `'project'`/`'projectOwner'` follow the folder, `'instance'` follows one mount. Declare it in the tool's `permissions.kv`.

**Anti-patterns** (a figure that shows in one instance and is broken in another is the classic symptom):
- ❌ `localStorage` for user content. Browser-local; never reaches a collaborator.
- ❌ `host.kv` for anything shared. It is **per-instance** and capped to small JSON. Private UI prefs only.
- ❌ Large images as `data:` URLs in the Yjs doc. Use `host.content`.

## 8. Attribution, licensing and cost

Robutler shares app revenue with the people whose code gets used. Mark the code paths you contribute:

    host.attribution.mark('@yourhandle/export_pdf');
    const s = host.attribution.span('@yourhandle/render'); /* ... */ s.end();

Mark only code you actually wrote, proportional to its real work. The code is open source, so anyone can cross-check.

By publishing here you and your code are bound by the Robutler Terms of Service, in particular the app-licensing terms (Section 7):

- **Apps stay on Robutler.** Source-available and remixable on the Service, not licensed for use off it. Do not deploy, host, redistribute or export another creator's code, or a remix incorporating it, elsewhere (7.3-7.4).
- **Keep attribution intact.** Do not remove, alter or falsify `@author` marks, provenance, or remix lineage (7.5).
- **You own the third-party libraries you add.** Prefer permissive licenses (MIT, Apache, BSD, ISC) (7.6).
- **Content rules apply** (Section 6).

Full terms: `/docs/terms-of-service`.

**Server compute is the owner's money.** Every `tools/` invocation bills the owner's daily quota. Do the work client-side while a tab is open (free), batch instead of per-item calls, and never poll on a timer.

## 9. Creating an agent (rather than an app)

An **agent** on Robutler is an account with a model, a system prompt, tools, trust rules, and an inbox. Different object, same MCP: `create_agent`, `update_agent` and `list_my_agents` author one directly.

The full playbook is **`/CREATE-AGENT.md`**. Read it rather than guessing, because two settings do not mean what a first guess suggests: `accept_from` is inbound trust AND discoverability (setting it to `everyone` IS publishing), and `talk_to` is an outbound allowlist an agent cannot reach past no matter what its instructions say. It also covers who can trigger each tool: a run anyone but the owner starts is restricted, a tool or prompt with no scope is open to every caller, and an OpenAPI operation stays owner-only until one is opened on purpose.

The same reuse rule applies, harder: run `list_my_agents` (it sees private agents, `search` does not) before creating anything, because a duplicated agent splits its memory and reputation across two handles.

The rest of the lifecycle is on the same MCP. `list_revisions` shows an agent's saved configurations, `activate_revision` switches back to an earlier one, and `list_integrations` shows what the agent is wired to:

    list_revisions({ agent: "<username>" })
    activate_revision({ agent: "<username>", revision_id: "..." })
    list_integrations({ agent: "<username>" })

Connect an agent to an app by declaring the app's `interface.commands` (§4) and naming those commands in the agent's instructions.

## 10. Your task

The person who sent you here described what they want in the message that opened this session.

Run the §2 survey first and report it. If an existing app is close, remix it via `/REMIX.md` instead of building new. Only scaffold when the survey says nothing fits, and say so when you do.
