theprototype is open core: this MIT repo (theprototype-app/core) is the entire
engine — self-hosted, peer-to-peer, exactly as it runs today. Registration, rooms,
roles and persistence are a separate closed cloud product
(theprototype.app-cloud) that plugs into the engine through the seams described
here. With no cloud plugin configured, these seams are inert: the OSS build
behaves byte-for-byte as it did before they existed.
Anyone can build their own plugin against the same contract — roles, gating, custom identity — without forking the engine.
At boot, startCloudPlugin() (src/lib/cloudPlugin.js)
dynamic-import()s a plugin URL if one is configured (first match wins):
| Source | Use |
|---|---|
VITE_CLOUD_PLUGIN (build env) |
the production cloud deploy bakes in its URL |
localStorage.cloudPluginUrl |
dev override — load a local plugin against a stock build |
A plugin is any ES module exporting register(cloudApi) (or a default export with a
register). It runs once, after the app mounts. A load/throw failure is caught and
toasted — the app keeps running in local mode.
Try it: localStorage.setItem('cloudPluginUrl', '/cloud-plugin-example.js') then
reload. The worked reference plugin is
static/cloud-plugin-example.js.
export function register(api) {
api.version // contract version (currently 3 — see "Versioning")
api.setPluginInfo({name, version}) // shown in Settings ▸ About (null clears)
// Receive-side capability gate (roles enforcement)
api.setCapabilityProvider(fn) // fn(peerId, msgType) => boolean; false = DROP
api.setAuthProvider(provider) // { authorize(peerId): boolean }
api.getAuthProvider()
// Shared state
api.appNotice // the first-run banner store; set(null) clears it
// Context
api.getPeers() // the live PeerConnection (or null pre-connect)
// Plugin message channel (replicate the plugin's OWN state across the mesh)
api.sendCloud(payload) // broadcast { type:'cloud', payload } to peers
api.onCloudMessage((peerId, payload) => …) // receive them
// UI mount points — mount fn: (el) => cleanup
api.mountConnect(fn) // into the Connect pill (login / Browse Rooms)
api.mountUsersSection(fn) // into the Users popover (roles)
api.mountProfile(fn) // into the profile dropdown (account) — v2
api.mountSettingsSection('account', fn) // Settings ▸ Account (only while mounted) — profile-notify
api.openSettings('account', 'an-element-id') // open Settings on a page, at one element of it — uir-account
api.mountConnectDrawer(fn) // into the Connect info drawer (room settings) — v2
api.mountSidebar(fn) // a ROW under Save in the logo menu (Publish) — v3
// Roles / presence bridges (core renders, the plugin decides)
api.setRolesInfo(info) // { myId, myRole, amAdmin, order, roleOf, setRole } | null
api.setScenePresence(data) // who is in the project's OTHER rooms | null — v2.4
api.setLockMode(mode) // 'select' | 'edit': the room's lock mode (host / admin only; false = refused) — 80a
api.lockMode.get() / .subscribe // the current {mode, at}; everyone follows the host's value
api.setAccountIdentity(id) // {username, avatar, email} | null — the collaborative identity
api.currentScene() / api.playModes() / api.peerRoster() / api.sessionHost()
api.connectToPeer(peerId) // dial through the normal request flow
api.captureThumbnail(maxW) // Promise<Blob | null> — a fresh JPEG of the viewport
// Publish · play · remix seams — v3 (roadmap #28-A), see "4. Publish, play, remix"
api.buildSceneBundle(opts) // Promise<{blob, meta}> — the open scene as a .tpscene
api.loadRemoteScene(entry) // Promise<boolean> — a remote .tpscene into the editor
api.camera.pose() / setPose(p) / bookmarks() / recall(id)
api.startPlay() / api.stopPlay()
api.setCommunityProvider(p) // swap the Templates ▸ Community source (null restores GitHub)
api.setProblemReporter(r) // 37 R20: where "Report a problem" sends ({submit, account}) — typeof-probed
api.toast(message)
}Every member added after v1 is additive: probe it with typeof and the plugin keeps
working against an older engine. When a plugin depends on a member, it declares the
contract it needs (export const compatibleHooks = 3) and the loader fails closed on an
older engine — see "Versioning" below.
One choke point at the top of conn.on('data') in
src/lib/peerHandler.svelte.js: a message is applied
only if canApply(sender, type) is true. Default (no provider) = allow everything.
A plugin's provider returns false to drop a sender's message types — this is the
receive-side layer role enforcement needs (a viewer's mutations never apply,
even if they send them).
A small floor of connection/handshake types is always allowed regardless of the
provider (hosts, userdata, locked, and the get* late-join requests) so a
plugin can never brick the mesh. A throwing provider is treated as allow, same
reason. Everything above the floor is the provider's decision (keyed on the
sender's role).
Pair it with send-side gating in the plugin UI (disable a viewer's gizmos/menus) so the app doesn't merely swallow actions silently.
Worked example — scene wipe: { type: 'clearscene' } is deliberately not in the
always-allowed floor, so a roles provider can drop it from viewers (the reference
cloud plugin's viewer allowlist already excludes it). Core pairs that with its own
send-side gate: a viewer pressing Clear scene gets the view-only toast instead of
clearing — a local clear whose broadcast peers drop would silently desync the viewer.
The gate lives in src/lib/objectPermissions.js
consumers and is inert without a plugin (isViewer() is false when no rolesInfo
is published).
Consulted in handleConnection when an unknown peer connects: if the auth provider's
authorize(peerId) returns true, the peer is accepted without a manual Approve.
Default (no provider) keeps the whitelist + approval flow byte-identical. authorize
is a synchronous lookup against state the plugin maintains from its own async login.
Automatic admissions are never silent (fix-live F-5). Whenever decide answers
'admit' (or authorize returns true), core shows the HOST a toast and a
notification-history entry that keeps its buttons until answered: Remove (closes the
link, drops the roster row, refuses that peer's re-dials while the tab stays open) and,
when the provider offers it, a switch-off. The optional provider member
admitNotice(peerId, cloudMeta) → {text?, turnOff?, turnOffLabel?} | null supplies the
line (≤ 200 chars) and the switch-off; absent or null = a generic line, no switch-off.
api.setConnectBadge({text, title?, onClick?} | null) puts a small badge on the Connect
pill (#connect-setting-badge, ≤ 32 chars) for a standing setting such as "Public ·
guests join"; a press runs onClick or opens the drawer's Rooms tab.
Roles replicate over the plugin message channel: an admin broadcasts the roles
map with sendCloud(payload); every peer's plugin applies it via onCloudMessage
and updates its capability provider. Core routes { type:'cloud', payload } and
never gates it (it's in the always-allowed floor), so role updates always arrive.
mountConnect / mountUsersSection / mountProfile / mountConnectDrawer /
mountSidebar hand the plugin a DOM node (via
CloudSlot.svelte) and an optional cleanup fn, so a
separately-built plugin owns its own rendering with no coupling to the app's
framework version. The appNotice store (the first-run banner) is a ready-made
shared-state seam a plugin can rebrand or clear.
Seven seams so a community tier (publish a scene, open a published one, remix it) can be built entirely in a plugin. Each is inert without one; none of them adds a peer message type — publishing is an upload, a remix is a local load.
The open scene as a .tpscene — the SAME payload builder and zip writer Save uses
(sessions.buildSessionPayload → exportSessionZip, packs never bundled), so a published
file is exactly a saved one. It never saves, names or renames anything locally: publish is a
copy out. name is the file's own name and defaults to the open scene's name, else
'Untitled'.
blob is application/zip. meta is read out of the payload the bundle was built from:
| field | meaning |
|---|---|
objectCount |
number — top-level objects in the scene (payload.count) |
hasFlow |
boolean — any graph has nodes (every scene carries an empty graphs.scene, so "a graph exists" is never the test); false when flow: false |
hasAudio |
boolean — a music track, a cable patch, or any node of the audio family (the catalog's Music group + sound, read at build time) |
hasGame |
boolean — the scene carries a game shell |
modules |
{id, version}[] — the modules the scene needs (the handshake's shape); [] when flow: false |
appVersion |
string — the app that built it |
bytes |
number — blob.size |
camera |
{position: [x,y,z], target: [x,y,z]} | null — the editor view at build time |
duration |
number | null — seconds: the music track's length, else the longest authored clip, else null |
files |
sessionFileList(payload) — the file rows a "what is big" toast lists |
Fetch a remote .tpscene and load it through the existing session path: the viewer gate,
the format confirm, the "Backup before " stash, the replicated clear+rebuild and the
peer-consent proposal all apply. This is "Open in ThePrototype" and "Remix". Resolves
true when the scene was applied; false when refused, declined or failed (the user
already saw why).
For the hero shot (recall a bookmark → captureThumbnail → restore) and for storing the
pose on the published record — bookmarks live in localStorage only and never travel
with the file. Every call answers null/false before the renderer exists and in VR.
| member | contract |
|---|---|
pose() |
{position: number[3], target: number[3], fov: number | null} | null — the current editor view. fov is additive: hand the whole object back to setPose to restore a lens a recall changed |
setPose({position, target, fov?}) |
boolean — moves the editor camera instantly (no tween; a capture may follow on the next frame). Writes both ends and updates the controls; bumps the camera claim so any continuous driver steps aside |
bookmarks() |
{id, name}[] — the saved views, for a "Camera" dropdown |
recall(id) |
boolean — jump to a saved view (position, target, saved FOV; the saved clip planes are a persisted local preference and are left alone). false when the bookmark is gone (deleted since the dropdown rendered) — fall back to the current view and say so |
The Controls button's own press and the canonical exit, so /?s=<id>&play=1 can land in
play mode after its load. Browsers grant a pointer lock only inside a user gesture:
called from a boot deep link the mode still holds (a refused lock never exits play) and
the pointer locks on the player's first click. stopPlay returns true when we were
playing.
A CloudSlot rendered directly under the Save row's format segment in the logo menu
(Sidebar.svelte) — the Publish row must sit beside Save or nobody finds it. Mount fn:
(el) => cleanup; null unmounts. Render a plain
<button class="side-row"><span class="side-ico">…</span><span>Publish</span></button> —
the sidebar republishes its row look under the slot, so a foreign button reads as a native
row (#sidebar-cloud-slot wraps it). Nothing renders without a plugin.
Swap the Templates modal's Community tab source. Core never learns what is behind the
provider; null restores the PR-gated GitHub gallery (a logout must be able to take the
swap back). The card shape is the gallery's, plus four optional fields the card renders
only when present:
api.setCommunityProvider({
// REQUIRED. The rows to show; core normalizes them. Return [] for the empty state, throw
// for the error state (the Retry button calls list({force: true})).
list: async ({ force }) => [{
slug, title, description, author, license, tags, modules, // the gallery.json fields
bytes, // number, for the size label
scene, thumb, // OR sceneUrl, thumbUrl — absolute URLs pass through untouched
id, href, likeCount, remixOf // optional: record id, page URL, ♥ count, {id, title?, href?}
}],
// REQUIRED. A card click. Return true when the scene was applied (the provider may
// simply call api.loadRemoteScene(entry)).
load: async (entry) => api.loadRemoteScene(entry),
// OPTIONAL. ONE quiet row above the grid; null for none. Re-read on every list().
notice: () => ({ text: 'Signed in as …', href: 'https://…' }),
// OPTIONAL. Replaces "Submit yours on GitHub" — a link (href) or an in-app action.
submit: { label: 'Publish this scene', action: () => openPublishDialog() }
})A provider swap while the tab is showing re-lists from the new source; anything without a
list function reads as null. While a provider is installed the tab's pull-request copy
stands down (it would be a claim about a source core knows nothing about).
Every member below is typeof-probed by the plugin; without a plugin nothing listens and the
two stores stay null, so the OSS build is unchanged. Core keeps a scene's permanent game
id (gameId, a UUID) in session.json — minted at the first deliberate save / export /
publish, kept by every ordinary save, forked (new id, parentGameId = the old) by a copy
(Explorer Duplicate, paste, Templates ▸ Save to Library) and by a REMIX at its first save.
The "Made with ThePrototype" badge links ?ref=export&g=<gameId>&b=<build>&src=<play|itch| static|embed>. Core never talks to a server about it.
| member | contract |
|---|---|
game.current() |
{gameId, parentGameId, template, pendingFork} or null. pendingFork: a remote scene opened by a non-owner — gameId is still the original's until the first save |
game.ensure() |
the open scene's game id, minted (or forked, for a pending remix) if needed |
game.fork() |
a NEW id whose parent is the current one — the answer when the server says the id belongs to another account |
loadRemoteScene({…, keepGameId?}) |
keepGameId: true = the OWNER opening their own published scene (no fork); otherwise a community load is a remix |
onExportBuilt(fn) → off |
after an export zip is built: fn({gameId, buildId, preset, title, template, parentGameId, appVersion}) |
onTemplateOpen(fn) → off |
a Games-tab template was started: fn(slug) (one "template open") |
onFunnelEvent(fn) → off |
76 FW2: one anonymous first-visit funnel event fn({e, c, b, d, x}) — closed vocabularies only (event name, Welcome answer, release, desktop/touch/vr, a time bucket or quest step), never an id. Core has already applied once-per-browser, Do Not Track / Global Privacy Control and the under-test guard; events from before registration are queued (20 max) and handed to the first listener. With no plugin nothing is sent anywhere. Probe with typeof |
funnelEvent(name) → Promise<boolean> |
76 FW2: the plugin's own funnel event through the same rules; only 'ob_waitlist' (a feature-update opt-in) is accepted |
onPlayStats(fn) → off |
102 M4: one anonymous play-statistics beacon fn({v: 1, s, d, e}) for the PUBLISHED scene the page was opened with (s = its ?s= id, d = desktop / phone / headset, e = up to 8 of {k: 'start'} / {k: 'end', t: <time bucket>, l: <level name>, g: <state>, w: 1 | -1}), at most 16 events per play, sent when the page is hidden or left. Core has already applied Do Not Track / Global Privacy Control, Settings ▸ Privacy ▸ Count my visits anonymously and the under-test guard; never an id of the player, tab or device. fn must send SYNCHRONOUSLY (pagehide) and return true when it went out — anything else and core tries again on the next hide. No queue: with no plugin core collects nothing. Probe with typeof |
toast(message, actions?, {keep?}) |
fix-live F-2: with keep: true an action toast's buttons also stay on its notification-history entry until one is pressed (a role offer the user sees later) |
setPeerMenuItems(items) |
fix-live: [{id, label, run(peerId, {name})}] (≤ 8, labels ≤ 40) appended to the Users peer menu (right-click a peer) under core's own entries — the cloud's "Report…"; [] clears |
removePeer(peerId, {block}) |
71 TR7: the Users menu's remove / remove-and-block, for a plugin enforcing its own list. The same permission rule applies (host or admin): returns false with a toast otherwise. Additive, probe with typeof |
setRoomAccess(p | null) |
71 AS3: the room-access fixes the block toast offers when the host blocks a GUEST (a session block holds a peer id; a guest comes back with a new one). p = {isGuest(peerId) → boolean | null, requireApproval() → void|Promise, signedInOnly() → void|Promise, state() → {gated?, signedInOnly?}}, every member optional. Core always offers its own "Require approval to join" (this session: every automatic join, invite links included, becomes the approval card) and also calls requireApproval(); "Signed-in people only" shows only when signedInOnly exists; isGuest() === false keeps the plain toast (the account block list holds). Null = the OSS toast. Additive, probe with typeof |
setConnectorProvider(p) |
86 B1/B5: the Claude connector's account half — {pair({resume}) → {wsUrl, pairingToken, replaces?, connections?}, connections() → {connections, tab?}, revoke(id), revokeAll(), account() → {signedIn, name?}} (pair rejects {code:'signin'} signed out); core draws Connect Claude, the connected indicator and Settings ▸ Account ▸ Connected apps only while one is installed and runs every relayed call through tpAgent; null removes it |
mountConnectorSignIn(fn) |
86-fix N1, FW-AI (76): any function = the connector is built in and nobody is signed in. Core draws "Sign in to connect" in the AI window (welcome card, or the header when a provider is set up) and it opens the profile pop-up, where mountProfile's section signs in; fn itself is not rendered. Once signed in, install the provider and pass null |
mountSettingsSection(key, fn) → boolean |
profile-notify (1.64): fill a Settings section; only 'account' so far — Settings ▸ Account, a page in its own "Account" group that exists only while a plugin has mounted into it or a connector provider is installed (the OSS Settings has none). The plugin's groups come first (Email, Sign-in methods, Devices — uir-account moved the last two out of the profile menu); core's Connected apps follow. Draw cards as section.sec-card-wrap with an [data-section-label] title and rows as .setting-row with an .sr-name, so Settings search finds them. A non-function removes it; an unknown key returns false. Probe with typeof |
openSettings(section, anchor?) → boolean |
uir-account: open Settings on a page — a deep-link key ('account', 'interface'…; 'connectedapps' is an alias of Account) — and, with anchor, scroll to the element with that id once it renders (it may arrive after an await; up to 4 s) and flash it. A malformed key or id returns false and opens nothing. Probe with typeof |
notificationOn(kind) → boolean |
profile-notify (1.64): the per-device switches in Settings ▸ Interface ▸ Notifications (src/lib/notifyPrefs.js). The plugin asks before an automatic pop-up: 'roomInvites', 'contests'; an unknown kind is true. Probe with typeof (absent = show, as before) |
setConnectBadge(badge | null) |
fix-live F-5: {text, title?, onClick?} — a small badge on the Connect pill for a standing setting (e.g. "Public · guests join"); null hides it. Probe with typeof |
setSceneHeart(info | null) |
the heart on the play-link start card (#embed-heart) and a game's pause menu (#game-shell-heart): {count, liked, toggle() → Promise<{liked, count} | null>}; null from toggle rolls the optimistic flip back |
The community provider gains three optional entry fields — liked (boolean, the viewer's own
heart), mine (boolean, the viewer's own scene), notice (one line on the card, e.g.
"Hidden by moderation: …") — and two optional provider members: mine: true shows the
Mine chip (#templates-chip-mine, filters entry.mine), and toggleLike(entry) → Promise<{liked, likeCount} | null> puts a heart on every card ([data-card-heart]).
A play link's frame may carry &src=play|embed&b=v<n> (read once with embed=1;
playMode.embedSource / embedBuild) — the badge inside counts them.
The Templates modal has ONE search field (#templates-search) on every tab: core filters the
cards client-side — every word must appear in the title, description, author or tags
(communitySearch.matchesQuery) — so the OSS GitHub gallery is searchable with no server. Two
optional provider members widen it on Community:
| member | contract |
|---|---|
search: true |
list() also receives q (lower-case, single-spaced, ≤ 60 chars, debounced 300 ms) when the field is not empty; search the same fields server-side so a returned row also passes core's filter. An older query's late answer is dropped |
sorts: [{id, label}] |
≤ 5 chips beside the field (#community-sorts [data-sort]); the FIRST is the default and is never sent — another chip's id arrives as list({sort}) |
Absent = absent: a provider that declares neither is called list({force}) exactly as before
and is never re-listed for a query. While a re-list runs the grid stays up and
#community-searching says "Searching…"; an empty answer to a query reads "No scenes match".
Core draws the whole report — the screenshot taken at the press, boxes drawn round what is wrong, the note, an explicit consent box — and calls the reporter only when the person presses Send with the box ticked. Without a reporter (no plugin, or an older plugin) the report is kept on this device as a Profiler recording and the card offers no Send.
| member | contract |
|---|---|
reporter.submit(report) |
report = {note, marks: [{x, y, w, h}] (fractions of the picture, ≤ 12), meta: {version, build, scene, device, url (no query), viewport, xr, peers, at}, perf: T1 light window | null, shot: Blob (JPEG) | null} → Promise<{ok, id?, reason?, error?}>. reason: 'signin' = the card keeps itself open and says where to sign in |
reporter.account() |
{signedIn, name?} — read when the card opens and every 1.5 s while it is open; Send is off until signedIn |
In a headset (VR menu ▸ Profile ▸ Report a problem) there are no boxes: the VR keyboard's title says that Enter sends the report, which is the consent.
Published scenes deep-link through the query string (/?s=<id>[&play=1][&remix=1])
so they never collide with an invite's #<peerId> hash. Core reads only the presence
of s (whatsNew.hasDeepLink()): the first-run welcome overlay stands down for that
boot exactly as it does for an invite. What the id means, fetching the record, loading it
(loadRemoteScene) and honouring play=1 (startPlay) are the plugin's.
A deployment may serve the same build from a second origin (VITE_PLAY_ORIGIN, e.g.
https://play.theprototype.app) and send play links and embeds there, so a played scene runs on a
page that holds none of the editor's storage. api.playOrigin is true on that origin (the page is
player-only for its whole life, the embed chrome) — a plugin must not offer sign-in or keep a token
there. api.playUrl('/?s=<id>&play=1') is the absolute URL to put in a play link or an embed: on
the play origin when one is configured, else on this origin. Probe both (typeof): older engines
have neither. VITE_APP_ORIGIN is the editor origin the player's "Open in the app" link returns to.
Five members for a tier that keeps scenes and whole projects on a server (cloud saves, rooms that survive
everyone leaving). Each is inert without a plugin: nothing subscribes until onSceneChange is called.
| member | contract |
|---|---|
sceneRevision() |
a number that moves on EVERY scene change — objects, graphs, animation, looks, sky, physics, music, HUD, game state — local or replicated from a peer (autosave's own dirty signal). Compare two reads to know whether anything changed between them. 0 before boot |
onSceneChange(fn) → off |
fn(revision) after every change from now on, never for the current value. A throwing listener is logged and never breaks the others. What a room's autosave listens to |
sceneSignature() → Promise<string> |
the CONTENT identity of the open scene: a short hash over the meaningful fields only (no uuid/createdAt/thumbnail, no latest-wins stamps, no game state — core's own "has this scene changed" signature). The revision above also moves on internal refreshes, so "did the scene really change since the version I saved or loaded?" compares two of these. buildSceneBundle({signature: true}) returns the same string as meta.signature (opt-in: one more pass over the payload) |
buildProjectBundle({versions?}) → Promise<{blob, meta}> |
the whole PROJECT as a .tp — the Explorer's own "Export project" bytes (manifest, every scene and library item; the stored "include versions" preference unless versions says otherwise). Downloads, names and changes nothing. meta = {name, scenes, assets, items, bytes, appVersion} |
openRemoteProject({url, title?}) → Promise<counts | null> |
fetch a .tp and OPEN it through core's own path — the format gate and the "This replaces your current project" confirm. Viewer-gated like loadRemoteScene. null when refused, declined or failed (the user already saw why) |
102 M2 (additive, typeof-probed, no version bump): buildArModel() → Promise<{blob, bytes} | null> — the open scene as a USDZ for AR Quick Look (every visible mesh, world-posed, floor-anchored, textures capped at 2048 px; null with no meshes). A publish stores it beside the .tpscene so the scene's page can offer "View in your room" as <a rel="ar" href="….usdz"><img …></a> (the anchor's first child must be an image or picture), shown only where AR Quick Look exists (iOS / iPadOS Safari: document.createElement('a').relList.supports('ar')).
A plugin restoring a SCENE uses loadRemoteScene({sceneUrl, keepGameId: true}) — the owner reopening their own
scene keeps its game id instead of forking it as a remix.
Objects and materials are validated on receive and on load. Every three.js object JSON core takes from a
peer, a file or its own stores passes src/lib/sceneSchema.js (through
src/lib/loadGuard.js) before three parses it, and so does every multi-slot materials payload. A CI step
(npm run check:loaders) fails on a generic three loader called anywhere else in src/.
What a module or plugin can rely on, and what it must keep to:
| the rule | |
|---|---|
| object types | three's own (Object3D, Group, Mesh, SkinnedMesh, InstancedMesh, Line*, Points, Sprite, LOD, Bone, the two cameras, the lights). Anything else arrives as an Object3D with its children |
| material types | the standard ones (Mesh*Material, Line*Material, PointsMaterial, SpriteMaterial, ShadowMaterial). Any other material arrives as the standard fallback material; custom looks are made with the shader graph |
| fields | the fields three's toJSON() writes for that type, each with a value rule. An unknown field is stripped; a bad value is stripped and three uses its default |
| images | embedded data URLs only, each under a size cap |
userData |
any plain JSON under a size cap (no __proto__ / constructor / prototype keys, bounded depth). The keys core and the shipped modules write keep a per-key kind |
Every change is counted (the wire diagnostics and one toast per session), never silent. The inventory
(scripts/schema-inventory.cjs, kept as tests/fixtures/schema-1.65/inventory.json) found that the shipped
modules build only the types above and write only plain-JSON userData, so modules get no registration
call. A later release that saves a new field adds it to the type's table in sceneSchema.js with a value
rule and a fixture in tests/unit/sceneSchema.test.js; a new userData key needs nothing.
CLOUD_HOOKS_VERSION (src/lib/cloudHooks.js) is the contract
version and api.version reports it. A plugin declares the contract it needs with
export const compatibleHooks = N; the loader refuses to register (toast, local mode)
when N is newer than the engine, and a new engine always accepts an older plugin
(every hook is inert without a consumer). History: 1 (M1) · 2 (roadmap #14: profile and
drawer mounts, roles bridge) · 3 (roadmap #28-A: the publish · play · remix seams above).
A coupled change therefore deploys the engine first and the plugin after.
The module api has its own number (101 F6): api.version on the module api (src/lib/sdk/core.js
SDK_API_VERSION, now 3) is NOT the plugin api.version above. Version 2 also notes that the raw
renderer handle a module (or a plugin's captureThumbnail path) can reach today stays for now and will
leave the contract once roadmap 100 swaps renderers: modules use the look / post SDK calls. Every
renderer the app makes is created in src/lib/render/ (a CI check keeps it that way).
Version 3 (2.0-n3c, additive): the SCRIPT api that Script nodes and a module's behaviours run with
(api inside the code) has a number of its own, api.version = SCRIPT_API_VERSION in
src/lib/scriptIO.js, now 2: 1 (absent) = object, raycast, keys, spawn; 2 adds self() (this
node's id) and stamp(input) (the newest trigger stamp on one of this node's inputs, in synced seconds,
null = never), both reads of replicated state so a value script stays deterministic. Inside a script,
probe (api.version ?? 1) >= 2; a module probes its own api.version >= 3 before writing such code.
Separate from the plugin contract: two PEERS agree on a session protocol before any scene data
flows. Every dial carries {jr: 1, proto: <int>, caps: {…}} in its PeerJS metadata (plus cloud,
invite, kind when they apply), and the modules handshake message carries the same proto and
caps beside wb / fc / dev. WIRE_PROTO lives in src/lib/wireProto.js
and is 1; a peer that sends no proto speaks 1 (every build up to 1.65).
- Same number: everything as before. Different (or unreadable): the link is refused before
any whitelist, approval card or data: a refusal dial (
joinresult: 'denied'+refuse: {reason: 'proto', need}) when the dialer can hear one, else a{type: 'refuse', reason: 'proto', need}message on an open link.needis the refuser's own protocol. The lower side shows "This session uses a newer version. Reload to update."; the higher side lists the other in People as needing to reload. No reconnect window, no mesh-fill redial; a later dial on the right protocol gets in. Only an answer to something this side asked for (a join request still waiting, or a link of ours to that peer) can latch the reload notice; the same claim in a stranger's dial shows a plain toast at most once a minute, a blocked peer or an unreadable number is closed without a word, and refusal dials the app sends by itself are bounded (5 a second and 20 in flight; 2 and 5 for dials nobody asked for; one per peer a second, the newest answer replacing one in flight); a person's own Reject or Full always goes out. - Bump
protoonly when a message changes meaning in a way an older build would apply wrongly. Additive fields and new message types do not bump it (an older build counts and drops a type it does not know); they become acapsflag instead — todaywb(batch envelopes),fc(fast movement channel),dev(a device row inmodules),lk(80a: object locks are stamped and gated —lockcarriesatsparallel touuids(when each object was taken, session clock), the handshake'slockedcarries every held object, an edit of an object someone else holds is not applied and the holder answerslockreject {uuid}plus the object as it is;lockmode {mode, at}from the host says whether selecting locks),slots2(105: a per-slot material value travels asmaterialParam/materialwith an additiveslotindex, and a slot'suserData.slot.offdraws the plain default; while a peer without it is connected, a per-slot gesture ends with one whole-listmaterialsmessage to that peer),slotShaders(105: ashadergraphdocument keyed<objectUuid>/<slotId>drives that one material slot; a peer without it keeps and forwards the document, draws the slot's own material and drops it from its own saves, and People shows "N people here use an older version — they do not see per-slot shaders" while one is connected and the scene holds a slot shader). Read a flag frompeerCaps; absent = the peer does not have it. - Inbound limits (F4): each peer has a per-second budget of messages and bytes and an
objectsize cap (src/lib/wireBudget.jsLIMITS, set at >= 4x the measured peaks); a message over budget is dropped and counted (budget:*in Diagnostics), the person is told once a minute, and the link stays up. Abatchenvelope costs one message plus one per four items, and eachobjectitem in it meets the size cap on its own; every data channel on the link is metered, and a goodbye or refusal passes the budget only a few times a second.
- Never trust the sender. The capability gate is receive-side truth; send-side UI is only ergonomics.
- Keep the provider cheap and non-throwing —
canApplyruns on every inbound message. - Dynamic-load only; a plugin is a separate build. Don't add a static import of plugin code into the engine (bundle + module-cycle reasons).