# Remix a Robutler widget

You're an AI coding agent helping someone **remix a Robutler widget** — a small, self-contained web app (an HTML/JS/CSS bundle) that runs sandboxed in an iframe on the Robutler canvas. This guide gets you connected and productive. (You fetched this file from a Robutler host; everywhere below, **"this host"** means that same origin.)

## 1. Connect the Robutler MCP server

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

- **URL:** `/mcp` on this host (e.g. `https://robutler.ai/mcp`) — Streamable HTTP transport.
- **Auth:** OAuth. Your environment opens a browser to authorize; approve as the widget's owner. There is **no API key to paste** — the OAuth flow handles it.

How to add it, per environment:

| 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 (or use a one-click MCP install deeplink) |
| **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. Tools you have

Once connected you'll see these (call `tools/list` if unsure):

- **`widget_download(folderId)`** — list + read the files in a widget bundle folder (returns each file's `id`). Text comes back inline up to a byte budget (default 200 KB); files past it are listed with `omitted: true`, so call again with `paths: [...]` for the ones you need. **Start here.**
- **`widget_put_files(folderId, files[])`** — write text files in the bundle (the EDIT step). Each file is either full-replaced (`{ path, text }`) or patched in place (`{ path, edits: [{ oldText, newText }] }` — prefer `edits` for large files so you don't re-send them; they work on files of ANY size, a multi-MB built `boot.js` included). UTF-8 text only, 32 MiB per file. Edits land in the live bundle: reload the mounted instance to see them (§3, step 5).
- `widget_remix(refId, via?)` — clone an app you can use into your **own private, editable copy** (returns its `widgetContentId` + `folderId`). Works on any app you can access, not just published ones; if the app reached you as a shared *document*, pass that document's id as `via` and the platform verifies the chain.
- `widget_instantiate(refId, …)` — mount an app on a canvas and get a live URL to preview. Pass a **widget id** (`widgetContentId`); an owned bundle `folderId` is auto-resolved to its widget. The result's `mountKind` must say `"widget"` — that is the difference between a running app and a file attachment.
- `widget_catalog(query?)` — the apps installed for this account, each with the `refId` it mounts by.
- `create_widget(name, template?)` — scaffold AND land a brand-new app in one call (bundle folder + private widget + dev token). For new apps, not remixes.
- `widget_scaffold(name, template?)` — starter files only; nothing is written server-side.
- `widget_publish(folderId)` / `widget_snapshot(workingWidgetId, …)` — deploy to the public catalog / cut an immutable release. These appear only on accounts with publishing enabled; without them your copy stays private, which does not stop it running or being shared.
- `widget_dev_token(…)` — mint a short-lived bearer so a locally-running widget can reach the portal.
- `widget_fn_logs(agentId, …)` — read a widget's server-side function logs when debugging.
- `workspace_list_open` / `workspace_widgets_list` / `workspace_widgets_invoke` / `workspace_widgets_logs` — drive and debug the LIVE instance in the user's open tab: `__reload` after edits, `__screenshot` to see it, logs for its console + load state.

## 3. The remix workflow

1. **Read** the bundle: `widget_download(<folderId>)`. Look for **`AGENT.md`** or `README.md` inside it — most widgets ship a remixer's guide with the architecture, the DSP/render parameters, and "how to add X" recipes. Read it before changing anything.
2. **Orient**: the entry point is usually `index.html` plus a main JS module; `widget.json` is the manifest (name, permissions, declared tools).
3. **Edit** the files with `widget_put_files(folderId, [{ path, text }])`. Keep the widget self-contained — bundle or CDN-load deps; don't assume a build step.

   **Exposing a new agent command:** the agent command surface is the **allowlist declared in `index.html`'s `<meta name="robutler:widget">` `interface.commands`** — it travels with the bundle, so your remix owns its own surface. Registering a handler at runtime (`host.commands.handle('foo', fn)`) is NOT enough: if `foo` is not in the meta's `interface.commands`, an agent calling it gets `unknown_op`. So when you add a command, add a `"foo": {"description": "…", "args": {…}}` entry to the meta too. **Footgun:** the meta `content='…'` is parsed with a tolerant regex — a single apostrophe (`'`) OR a `>` (e.g. in `->`) anywhere inside the JSON silently truncates it and drops your commands. Use `→` instead of `->` and avoid apostrophes in descriptions; after editing, sanity-check that the widget still lists all its commands.

   The widget 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 key/value — small JSON, NOT shared between two widgets viewing the same document; see §4), `host.fn` (call the widget's own server functions declared in `widget.json`), `host.content` (PROJECT-folder file storage — binaries shared across the whole document; see §4), `host.collab` (Yjs multi-user rooms — the shared document body), `host.commands.handle(name, fn)` (the agent-control commands declared in the `<meta name="robutler:widget">` tag), plus `host.live`, `host.user`, `host.discover`. The complete, authoritative surface is the TypeScript typedefs at **`/widgets/sdk.v2.d.ts`**; prose reference at **`/develop/sdk-v2`** and per-namespace guides under `/develop/` (`host-kv`, `host-content`, `host-fn`, `host-discover`, `host-collab`, `host-live`, `host-user`, plus the `widget-authoring` overview).
4. **Verify — the test gate (do this before publishing).** If the widget ships a bundled test suite (the Robutler widget test standard: a `tests/` folder with `manifest.json` + `runner.html`), **run it and confirm it is green BEFORE you publish.** The tests travel with the bundle, so your remix inherits them. Three equivalent ways, all at the edge (never the backend):
   - call the widget's own `runTests()` command (e.g. `window.<widget>.api.runTests()` / `host.commands.handle('runTests', …)`) → 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 a remix until the suite passes.** A red suite means your edit introduced a regression — fix it first. Surface the report to the user, and if the widget has `tests/runbooks/*.md`, run the relevant behavioral runbook too. (A widget with no `tests/` yet: still smoke-test the change before publishing, and consider adding the standard.)
5. **See it live.** Your edits land in the bundle folder the sandbox serves, so the running copy picks them up on reload: call `workspace_widgets_invoke(<itemId>, "__reload")` on the mounted instance (or have the user reload). **Cache footgun:** `__reload` refreshes the entry document but NOT sub-assets pinned with their own `?v=` token — when you edit a file that `index.html` references with `?v=`, bump that token too, or the old bytes keep serving with no error.
6. **Verify like you mean it.** A successful tool call is not a render. `widget_instantiate` must report `mountKind: "widget"`; `workspace_widgets_list` must list the instance; `workspace_widgets_logs` must reach `loadState: "ready"` (it refuses outright when an item is not a running app). `__screenshot` shows you the actual pixels.
7. **Publish, where available.** On accounts with publishing enabled, `widget_publish(<folderId>)` deploys to the catalog and `widget_snapshot` cuts a release. One nuance: plain HTML/CSS/JS edits go live on reload, but changes to `widget.json` or to the `<meta robutler:widget>` **command surface** are snapshotted onto your copy when it is created and refresh on republish — so declare the full command surface up front.

**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 when resolving relative module specifiers; Safari/WebKit does not, so an inline boot script that does `import('./app.js')` works in Chrome but fails in Safari with *"Module name, './app.js' does not resolve to a valid URL"* (the widget never loads). Resolve the entry against `document.baseURI` so `import()` always gets an absolute URL:

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

This only matters for the FIRST hop from the inline `<script type="module">` in `index.html`. Static `import`s inside `app.js` resolve against its own (now absolute) URL and are fine, and CSS links, `<script src>`, and import-map entries should already use absolute paths (`/widgets/...`, `https://...`), so they're unaffected.

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

A document is often open in **two widgets at once** (a second tab, a collaborator, a split view). They all join the same collab room, so the question for every byte you persist is: *will the other instance see it?* Store shared user-content in the **project folder**, never in per-instance scratch:

- **The document body / structured state** → the **collab room** (Yjs via `host.collab`). It's the shared CRDT; every instance sees edits live. This is where text, shapes, slides, rows, rig/tab state belong.
- **Binary media** (images, figures, audio captures, exports) → **`host.content.put(file, { name })`**. This writes a **name-addressed file into the open PROJECT FOLDER** (ADR-0022) — shared across every instance and every collaborator, and it travels with the doc on Share / Save-as. Reference it as `content://<name>` and resolve with `host.content.get(name)`.
- **Binding**: `host.content` is project-scoped only once the instance is bound to the project folder. Save binds automatically; **opening** an existing document must bind too — the shared collab-kit calls `host.documents.bind(projectFolderId)` for you on open. If you write a bespoke open flow, call `host.documents.bind(<folderId>)` yourself, or media will 404 in the second instance.
- **Server-side function state** (leaderboards, marketplaces, analytics roll-ups, anything a viewer must not be able to forge) → your `widget.json` tools get `ctx.kv.at(scope)` on the server: `'app'` is shared across every instance of your widget type (one leaderboard per game, zero config), `'project'`/`'projectOwner'` follow the project folder, `'instance'` follows one mount. Declare the scope in the tool's `permissions.kv` (e.g. `{ "app": "rw" }`); the platform resolves the partition from the mounted instance, so clients can't spoof it. A ready-made pair already exists — `host.fn.invoke('robutler/submit-score', { name, score })` and `host.fn.invoke('robutler/leaderboard-top')` give any widget a per-type leaderboard without writing a tool at all. Details: `/develop/host-fn`.

**Anti-patterns that break sharing** (a figure that shows in one widget and is broken in another is the classic symptom):
- ❌ `localStorage` for user content — it's browser-local; it never reaches the server, let alone a collaborator.
- ❌ `host.kv` for anything shared — it is **per-instance** (and capped to small JSON; never put binaries there). Use it only for that instance's private UI prefs (e.g. which mic, which theme).
- ❌ Embedding large images as `data:` URLs in the Yjs doc — it bloats the CRDT; put them in `host.content` instead.

## Who can call it (keep the original's access, never widen it)

Each server function in `widget.json` says who may call it with `httpAuth`: `session` is the app's owner only, `visitor_session` any signed-in person, and `public` anyone. A missing `httpAuth` means `public`. 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; runs other people start are restricted and do not offer it.

- Keep every `httpAuth` and `permissions` entry exactly as the original declares it. Never widen one in a remix.
- Check each function you add: if it reads or changes the owner's private data, or uses the owner's keys, secrets or connected accounts, make it `session`. `public` is for data anyone may see and for webhooks that verify their own signature.

## Attribution markers (credit your contribution)

Robutler shares app revenue with the people whose code gets used. When you add a feature, mark its code paths with YOUR handle so usage credits you:

    host.attribution.mark('@yourhandle/export_pdf');                       // a discrete action
    const s = host.attribution.span('@yourhandle/render'); /* ... */ s.end();  // time spent

- The leading `@yourhandle` names the maker of that code; use the handle of whoever wrote it. In your own remix it changes nothing, because your own code is already yours. It matters when you propose the feature back to the original: there it credits you once the owner merges it. A mark with no `@handle` is a place in the app's own code.
- Be fair and honest: mark only code you actually contributed, proportional to its real work. The code is open source, so the app owner (and anyone) can read your marks and cross-check. Disputes are settled in a public discussion, not by the platform.
- The app's rewards are sized by how much it is used (eye-time). Part of them is the app's code pool (30% unless the owner sets it, never under 20%), shared among the apps this one was remixed from (by how much of their code this app still contains, measured each time it is published), the libraries it pins (by the size of their code) and the people named in marks who accepted the credit; the owner keeps the rest. Everyone counts at most once per 10 second window, however often a mark fires and however many marks carry a handle, so `mark()` is safe in a loop and adding marks gains nothing. Deleting an original's marks from code you kept does not reduce what the original is credited for.

Proposing your feature back to the original (higher-traffic) app? See `BACKMIX.md`.

## Licensing and terms (important)

By remixing and publishing here, you and your code are bound by the Robutler Terms of Service, in particular the app-licensing terms (Section 7). For any app you remix or publish:

- **It stays on Robutler.** Apps are source-available and remixable on the Service, but are not licensed for use off it. Do not deploy, host, redistribute, or export another creator's code, or a remix that incorporates it, to any other platform (7.3-7.4). The export and download tools are for the owner's own backup, not for taking other creators' code off-platform.
- **Keep attribution intact.** Do not remove, alter, or falsify the `@author` or provenance marks or the remix lineage; doing so is both a Terms violation and unfair to contributors (7.5).
- **You are responsible for third-party libraries you add.** Make sure their licenses permit this use; prefer permissive licenses (MIT, Apache, BSD, ISC) and avoid components whose terms conflict with these terms (7.6).
- **Content rules apply.** Do not build apps that produce illegal, infringing, or abusive content (Section 6).

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

## 5. Your task

The person who sent you here had a **private copy** made for you to edit. The **widget id**, **bundle folder id**, and **name** are in the message that opened this session. The two ids split the work: the **widget id** mounts and previews (`widget_instantiate`), the **folder id** reads and writes files (`widget_download` / `widget_put_files`).

If the bundle ships an `AGENT.md` or `README.md`, read it first (via `widget_download`); otherwise orient from `widget.json` plus the entry HTML. Then ask them what they'd like to change.
