@hypersoniclabs/helix-sdk 0.1.1 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/README.md +954 -2
  2. package/dist/action-surface.d.ts +182 -0
  3. package/dist/action-surface.js +1032 -0
  4. package/dist/action-surface.js.map +1 -0
  5. package/dist/camera.d.ts +78 -0
  6. package/dist/camera.js +640 -0
  7. package/dist/camera.js.map +1 -0
  8. package/dist/dev-shell/criteria.d.ts +46 -0
  9. package/dist/dev-shell/criteria.js +98 -0
  10. package/dist/dev-shell/criteria.js.map +1 -0
  11. package/dist/dev-shell/index.d.ts +189 -0
  12. package/dist/dev-shell/index.js +287 -0
  13. package/dist/dev-shell/index.js.map +1 -0
  14. package/dist/dev-shell/keys.d.ts +14 -0
  15. package/dist/dev-shell/keys.js +78 -0
  16. package/dist/dev-shell/keys.js.map +1 -0
  17. package/dist/dev-shell/simulator.d.ts +436 -0
  18. package/dist/dev-shell/simulator.js +1634 -0
  19. package/dist/dev-shell/simulator.js.map +1 -0
  20. package/dist/dev-shell/state.d.ts +148 -0
  21. package/dist/dev-shell/state.js +196 -0
  22. package/dist/dev-shell/state.js.map +1 -0
  23. package/dist/device-definition-resolver.d.ts +34 -0
  24. package/dist/device-definition-resolver.js +172 -0
  25. package/dist/device-definition-resolver.js.map +1 -0
  26. package/dist/device-trial.d.ts +3 -0
  27. package/dist/device-trial.js +132 -0
  28. package/dist/device-trial.js.map +1 -0
  29. package/dist/devices.d.ts +228 -0
  30. package/dist/devices.js +198 -0
  31. package/dist/devices.js.map +1 -0
  32. package/dist/dreamerAudio.d.ts +126 -0
  33. package/dist/dreamerAudio.js +135 -0
  34. package/dist/dreamerAudio.js.map +1 -0
  35. package/dist/generated/runtime-contract.d.ts +15529 -0
  36. package/dist/generated/runtime-contract.js +20470 -0
  37. package/dist/generated/runtime-contract.js.map +1 -0
  38. package/dist/index.d.ts +364 -3
  39. package/dist/index.js +1954 -13
  40. package/dist/index.js.map +1 -1
  41. package/dist/interaction-mode.d.ts +172 -0
  42. package/dist/interaction-mode.js +553 -0
  43. package/dist/interaction-mode.js.map +1 -0
  44. package/dist/internal/avatar-pose.d.ts +25 -0
  45. package/dist/internal/avatar-pose.js +46 -0
  46. package/dist/internal/avatar-pose.js.map +1 -0
  47. package/dist/internal/keyed-collection.d.ts +2 -0
  48. package/dist/internal/keyed-collection.js +12 -0
  49. package/dist/internal/keyed-collection.js.map +1 -0
  50. package/dist/internal/vehicle-detach-action.d.ts +2 -0
  51. package/dist/internal/vehicle-detach-action.js +6 -0
  52. package/dist/internal/vehicle-detach-action.js.map +1 -0
  53. package/dist/matchmaking.d.ts +433 -0
  54. package/dist/matchmaking.js +1487 -0
  55. package/dist/matchmaking.js.map +1 -0
  56. package/dist/materials.d.ts +122 -0
  57. package/dist/materials.js +217 -0
  58. package/dist/materials.js.map +1 -0
  59. package/dist/multiplayer-accessors.d.ts +100 -0
  60. package/dist/multiplayer-accessors.js +200 -0
  61. package/dist/multiplayer-accessors.js.map +1 -0
  62. package/dist/multiplayer-contract/avatar-pose.d.ts +112 -0
  63. package/dist/multiplayer-contract/avatar-pose.js +250 -0
  64. package/dist/multiplayer-contract/avatar-pose.js.map +1 -0
  65. package/dist/multiplayer-contract/credential.d.ts +80 -0
  66. package/dist/multiplayer-contract/credential.js +5 -0
  67. package/dist/multiplayer-contract/credential.js.map +1 -0
  68. package/dist/multiplayer-contract/final-rest.d.ts +66 -0
  69. package/dist/multiplayer-contract/final-rest.js +38 -0
  70. package/dist/multiplayer-contract/final-rest.js.map +1 -0
  71. package/dist/multiplayer-contract/index.d.ts +20 -0
  72. package/dist/multiplayer-contract/index.js +41 -0
  73. package/dist/multiplayer-contract/index.js.map +1 -0
  74. package/dist/multiplayer-contract/messages.d.ts +731 -0
  75. package/dist/multiplayer-contract/messages.js +237 -0
  76. package/dist/multiplayer-contract/messages.js.map +1 -0
  77. package/dist/multiplayer-contract/room.d.ts +177 -0
  78. package/dist/multiplayer-contract/room.js +17 -0
  79. package/dist/multiplayer-contract/room.js.map +1 -0
  80. package/dist/multiplayer-contract/state.d.ts +241 -0
  81. package/dist/multiplayer-contract/state.js +15 -0
  82. package/dist/multiplayer-contract/state.js.map +1 -0
  83. package/dist/multiplayer-final-rest.d.ts +32 -0
  84. package/dist/multiplayer-final-rest.js +217 -0
  85. package/dist/multiplayer-final-rest.js.map +1 -0
  86. package/dist/multiplayer.d.ts +624 -0
  87. package/dist/multiplayer.js +2503 -0
  88. package/dist/multiplayer.js.map +1 -0
  89. package/dist/package.json +3 -0
  90. package/dist/protocol.d.ts +859 -1
  91. package/dist/protocol.js +117 -5
  92. package/dist/protocol.js.map +1 -1
  93. package/dist/runtime-contract/index.d.ts +15 -0
  94. package/dist/runtime-contract/index.js +12 -0
  95. package/dist/runtime-contract/index.js.map +1 -0
  96. package/dist/server-clock.d.ts +25 -0
  97. package/dist/server-clock.js +88 -0
  98. package/dist/server-clock.js.map +1 -0
  99. package/dist/tsconfig.build.tsbuildinfo +1 -1
  100. package/dist/universal-vehicles.d.ts +111 -0
  101. package/dist/universal-vehicles.js +2 -0
  102. package/dist/universal-vehicles.js.map +1 -0
  103. package/dist/vault.d.ts +562 -0
  104. package/dist/vault.js +365 -0
  105. package/dist/vault.js.map +1 -0
  106. package/dist/vehicle-specialty-placement.d.ts +28 -0
  107. package/dist/vehicle-specialty-placement.js +154 -0
  108. package/dist/vehicle-specialty-placement.js.map +1 -0
  109. package/dist/vehicle-specialty-transport.d.ts +78 -0
  110. package/dist/vehicle-specialty-transport.js +183 -0
  111. package/dist/vehicle-specialty-transport.js.map +1 -0
  112. package/dist/voice.d.ts +229 -0
  113. package/dist/voice.js +1348 -0
  114. package/dist/voice.js.map +1 -0
  115. package/generated/runtime-contract/helix-runtime-contract.json +13332 -0
  116. package/generated/runtime-contract/known-answer.json +20471 -0
  117. package/generated/runtime-contract/known-answer.schema.json +630 -0
  118. package/generated/runtime-contract/runtime-contract.schema.json +607 -0
  119. package/generated/runtime-contract/unreal/HelixRuntimeContract.generated.h +908 -0
  120. package/package.json +44 -5
package/README.md CHANGED
@@ -19,7 +19,11 @@ npm install @hypersoniclabs/helix-sdk
19
19
  ```ts
20
20
  import { Helix } from '@hypersoniclabs/helix-sdk';
21
21
 
22
- const { embedded, world, user } = await Helix.init(); // call once, at startup
22
+ const { embedded, world, user, runtimeFidelity } = await Helix.init(); // call once, at startup
23
+
24
+ // Pass the versioned intent to the engine's canonical fidelity resolver. The
25
+ // SDK never detects the device or derives subsystem budgets itself.
26
+ engine.resolveFidelity(runtimeFidelity);
23
27
 
24
28
  if (Helix.auth.isAuthenticated()) {
25
29
  const me = await Helix.auth.getUser(); // { id, username, displayName }
@@ -36,6 +40,23 @@ loginButton.onclick = async () => {
36
40
  };
37
41
 
38
42
  Helix.auth.onAuthChanged((user) => updateUi(user)); // login + logout
43
+
44
+ // Ask the HELIX shell to render native status notifications.
45
+ Helix.notify.success('Prize claimed', 'Welcome Chip added to inventory');
46
+ Helix.notify.failure('Purchase failed', 'Not enough LIX');
47
+ Helix.notify.notification('Quest updated', 'Return to the VIP lounge');
48
+ Helix.notify.message('Nova', 'Meet me by the arcade machines');
49
+
50
+ // Publish a current interaction prompt without tying your world to a renderer.
51
+ Helix.prompts.set({
52
+ id: 'fortune-arcade.vip',
53
+ title: 'VIP Room',
54
+ description: 'Buy a keycard to enter.',
55
+ input: { key: 'E', label: 'Interact' },
56
+ actionLabel: 'Buy keycard',
57
+ state: 'available',
58
+ });
59
+ Helix.prompts.clear('fortune-arcade.vip');
39
60
  ```
40
61
 
41
62
  When the world is opened directly (e.g. a local `vite dev` server with no shell), `init()` resolves
@@ -44,12 +65,737 @@ and embedded.
44
65
 
45
66
  ### API
46
67
 
47
- - `Helix.init(): Promise<{ embedded, world, user }>` — handshake; call once before anything else.
68
+ - `Helix.init(): Promise<{ embedded, world, user, runtimeFidelity }>` — handshake; call once before
69
+ anything else. `runtimeFidelity` is the validated versioned presentation intent, or `null` for an
70
+ older shell or malformed payload; in that case the engine retains its Auto fallback.
48
71
  - `Helix.auth.getUser(): Promise<HelixUser | null>`
49
72
  - `Helix.auth.isAuthenticated(): boolean`
50
73
  - `Helix.auth.requestLogin(): Promise<HelixUser>` — resolves on login, rejects on dismiss/unavailable.
51
74
  - `Helix.auth.onAuthChanged(fn): () => void` — fires on login and logout; returns an unsubscribe fn.
75
+ - `Helix.notify.show({ kind, title, message?, timeoutMs?, actionLabel?, actionHref? }): boolean`
76
+ - `Helix.notify.success|failure|notification|message(title, message?): boolean` — returns `false` when
77
+ the world is running standalone without a shell.
78
+ - `Helix.prompts.set({ id, title, description?, input?, actionLabel?, state?, priority? }): boolean`
79
+ - `Helix.prompts.clear(promptId?): boolean`
52
80
  - `Helix.getSessionToken(): string | null` — the world-scoped token, for advanced direct API calls.
81
+ - `Helix.hasLeft(): boolean` — `true` once the player has left this world through the shell (Exit,
82
+ browser Back). Room joins are refused from then on. See "When the player leaves the world" below.
83
+ - `Helix.onLeave(fn): () => void` — called once, synchronously, when the player leaves this world;
84
+ returns an unsubscribe fn. Not called for a subscriber added after the leave: read `hasLeft()`.
85
+
86
+ ### Economy & items (v2, shell-mediated)
87
+
88
+ All of these are **server-authoritative**: the world *requests*, the shell (which holds the player's
89
+ session) settles with the backend and renders the purchase popup. Reads degrade to empty defaults
90
+ when not embedded; a purchase returns `Unauthorized` (never a fake success).
91
+
92
+ ```ts
93
+ const { lix, coins } = await Helix.wallet.getBalance();
94
+ Helix.wallet.onBalanceChanged((b) => updateHud(b));
95
+
96
+ // World code names a registered distribution key; the shell shows Claim/Buy.
97
+ const res = await Helix.marketplace.purchaseDistributionKey('harbor_postcard', { quantity: 2 });
98
+ if (res.completed) displaySouvenirs(res.fulfilledQuantity ?? 0); // Granted | Claimed | AlreadyOwned
99
+ else showToast(res.status); // InsufficientFunds | Cancelled | …
100
+
101
+ await Helix.marketplace.purchaseProduct('golden_key'); // stable world-product key -> pkey:golden_key
102
+ await Helix.marketplace.purchaseDistribution('public_distribution_id'); // exact public primary route
103
+ await Helix.marketplace.purchaseListing('listing_for_serial_12'); // exact secondary serial
104
+ const items = await Helix.marketplace.getListings({ kind: 'home_item' });
105
+
106
+ const context = await Helix.marketplace.getPurchaseContext('dkey:harbor_postcard', { quantity: 2 });
107
+ // The shell/API own price, edition, fixed supply, remaining count and next serial.
108
+
109
+ // Ownership gating — works across worlds & creators (VIP / season passes).
110
+ if (await Helix.inventory.hasItem('vip_pass_001')) openBackstage();
111
+ const owned = await Helix.inventory.getMyItems();
112
+ await Helix.inventory.equipItem('vip_hat_001');
113
+ Helix.inventory.onInventoryChanged(refreshInventory);
114
+ ```
115
+
116
+ - `Helix.wallet.getBalance()` / `onBalanceChanged(fn)`
117
+ - `Helix.marketplace.purchaseDistributionKey(key, options?)` / `purchaseDistribution(id, options?)` / `purchaseListing(id)`
118
+ - `Helix.marketplace.purchaseProduct(productKey)` for world-local products/effects; it does not mint universal items or accept an internal product UUID
119
+ - `Helix.marketplace.getListings(query?)` / `getPurchaseContext(ref, options?)`
120
+ - `Helix.inventory.hasItem(id)` / `getQuantity(id)` / `getMyItems()` / `equipItem(id)` / `onInventoryChanged(fn)`
121
+
122
+ The SDK mints a stable idempotency key per purchase (reused across the popup's retries) so a dropped
123
+ network can never double-charge. Item-definition ids are deliberately not purchase references: use only
124
+ `dkey:`, `distribution:` or `listing:` through the typed methods above. See the backend `/api/v1/iwp/*`
125
+ endpoints for the settlement layer.
126
+
127
+ Collectible acquisition results expose `resaleEligibleAt`; exact listing context exposes a separate
128
+ seller `holdUntil`. The unified relisting cooldown is 24 hours after every acquisition. Basic requires
129
+ email; `verified` means unique verified mobile plus good standing. The type also accepts reserved
130
+ `identity_verified` and future `business_verified`. Payout holds are 3 days base and may be risk-extended
131
+ up to 15 days; never treat the relisting timestamp as payout availability.
132
+
133
+ ### Interaction prompts
134
+
135
+ `Helix.prompts` is intentionally engine-agnostic. A Three.js, Phaser, Unity WebGL, or plain DOM world
136
+ can all publish the same contract: a stable prompt id, display text, optional keyboard/gamepad labels,
137
+ and a coarse state (`default`, `available`, `locked`, or `busy`). The shell decides how to render it.
138
+
139
+ ### XR signals (engine ↔ shell)
140
+
141
+ Two document events connect an engine's XR module and the shell without either importing the other.
142
+ Both are sticky: the last detail is also recorded on `document`, so a late listener starts from the
143
+ current state.
144
+
145
+ - `XR_SESSION_EVENT` (`'helix:xr-session'`) — dispatched by the engine XR module on every immersive
146
+ session change, `detail: { state, reason?, source: 'humanoid-character' }`, sticky at
147
+ `document.__helixXrSession`. After `Helix.init()` the SDK forwards it to the shell as the
148
+ `helix:xr-session` message (and reports a sticky value once at init). Other sources are ignored.
149
+ - `XR_INTERACTION_PROMPT_EVENT` (`'helix:interaction-prompt'`) — dispatched by the SDK on every
150
+ `Helix.prompts.set/clear`, `detail: { prompt: { id, label, state? } | null, source: 'helix-sdk' }`
151
+ (`label` is the prompt's `title`), sticky at `document.__helixInteractionPrompt`, so the engine can
152
+ draw the prompt in-scene. The shell messages are unchanged.
153
+
154
+ ### Rich presence
155
+
156
+ Push a **live activity** for the local player that enriches the baseline "In [World]" their friends
157
+ already see (in the friends sidebar and on their profile) — e.g. `Racing — lap 3/5`. It's **dynamic**:
158
+ call it whenever the moment changes, no registration, no per-activity setup.
159
+
160
+ ```ts
161
+ // Enrich presence with whatever the player is doing right now.
162
+ await Helix.presence.setActivity({
163
+ state: 'Racing — lap 3/5', // required, ≤128 chars — the line friends see
164
+ details: 'Sunset Circuit', // optional second line, ≤128 chars
165
+ party: { current: 2, max: 8 }, // optional party sizing
166
+ // image: 'my-mode-icon', // optional; omitted → the world's thumbnail (zero-config)
167
+ // joinable: true, // hint only; joining an instance ships with the MP runtime
168
+ });
169
+
170
+ // e.g. drive it off game state
171
+ raceEvents.on('lap', (n, total) =>
172
+ Helix.presence.setActivity({ state: `Racing — lap ${n}/${total}` }),
173
+ );
174
+
175
+ // Back to plain "In [World]". Also happens automatically when the player leaves.
176
+ await Helix.presence.clearActivity();
177
+ ```
178
+
179
+ - `Helix.presence.setActivity(activity)` → `Promise<boolean>` — `true` on success; `false` for guests,
180
+ outside a shell, when not in a world, or when rejected. **Never throws** into your game loop.
181
+ - `Helix.presence.clearActivity()` → `Promise<boolean>`.
182
+
183
+ **Server-authoritative (by design).** `setActivity` posts to the authenticated presence endpoint using
184
+ the player's own session. The server sets activity **only for that player** and **only for the world
185
+ they're currently in** — a world can never write another player's status, or a world they aren't in.
186
+ This is the interim of the "the world's server sets it" model: when the multiplayer room runtime lands
187
+ it will set activity server-to-server after authenticating the player into its instance; the API and
188
+ validation are already shaped for that. Backend: `POST` / `DELETE /api/v1/users/me/presence/activity`.
189
+
190
+ **Privacy & safety.** Activity is governed by the player's presence privacy (visibility
191
+ `Everyone / Friends only / Nobody`, plus a *hide-activity* toggle) — if they've opted out, the server
192
+ never emits it, to anyone. Text is length-capped, rate-limited, and screened by the shared text
193
+ moderation layer server-side (a bad-actor world can't push junk into a friend's status card).
194
+
195
+ ### Durable storage
196
+
197
+ `Helix.dataStore` is per-world key–value storage — the place for anything that must survive a
198
+ session. A player's own session may write exactly **one** key, `player:${user.id}`, so put the whole
199
+ save in that single JSON document; sub-keys, world keys and room state are written by the game
200
+ server. Reads are world-open point-gets, and `list` returns keys only — values are never handed out
201
+ in bulk.
202
+
203
+ ```ts
204
+ await Helix.dataStore.set(`player:${user.id}`, { level: 4, coins: 120 });
205
+ const save = await Helix.dataStore.get<Save>(`player:${user.id}`); // null when unset
206
+
207
+ // Optimistic concurrency — read the version, hand it back, and a losing race is refused
208
+ // instead of silently clobbering the other writer.
209
+ const entry = await Helix.dataStore.getEntry<Save>(`player:${user.id}`); // { value, version } | null
210
+ const next = { ...(entry?.value ?? fresh), coins: (entry?.value.coins ?? 0) + 10 };
211
+ await Helix.dataStore.set(`player:${user.id}`, next, { expectedVersion: entry?.version ?? 0 });
212
+ ```
213
+
214
+ - `Helix.dataStore.get<T>(key)` → `Promise<T | null>` — `null` when unset, and in preview mode.
215
+ - `Helix.dataStore.getEntry<T>(key)` → `Promise<{ value: T; version: number } | null>`.
216
+ - `Helix.dataStore.set<T>(key, value, { expectedVersion? })` → `Promise<void>` — `expectedVersion: 0`
217
+ asserts create-only. Omit it and the write is last-writer-wins.
218
+ - `Helix.dataStore.delete(key, { expectedVersion? })` → `Promise<void>`.
219
+ - `Helix.dataStore.list(prefix?, { cursor?, limit? })` → `Promise<{ keys: string[]; nextCursor?: string }>` —
220
+ keys only, one page (≤100) per call; pass `nextCursor` back as `cursor` for the next page.
221
+
222
+ There is no multi-key transaction: design so no two keys must move together. In preview mode reads
223
+ return `null`/empty and writes no-op.
224
+
225
+ ### Leaderboards
226
+
227
+ `Helix.leaderboard` is keep-best per player, decided atomically by the backend — a worse score is a
228
+ harmless no-op, so resubmitting is always safe. Each board is ONE bounded document keeping its
229
+ declared top `size` (up to 100): scores below the cutoff are not stored, and `best` comes back
230
+ `null` when the player is off the board. Boards are declared per build (one must be named `main` —
231
+ the world's default board) and are usually written by the authoritative room; a session submits
232
+ only for **itself**.
233
+
234
+ ```ts
235
+ const { best, updated } = await Helix.leaderboard.submit('bestTime', lapMs, { order: 'asc' });
236
+ if (!updated) showToast(best === null ? 'Didn\'t place' : `Your record of ${best} stands`);
237
+
238
+ const { entries, truncated } = await Helix.leaderboard.top('bestTime', { limit: 10, order: 'asc' });
239
+ for (const e of entries) addRow(e.displayName, e.score);
240
+ ```
241
+
242
+ - `Helix.leaderboard.submit(board, score, { order? })` → `Promise<{ best, updated }>` — `order`
243
+ (`'desc'` default, `'asc'` for times) only decides direction while the board is new.
244
+ - `Helix.leaderboard.top(board, { limit?, order? })` → `Promise<{ entries, truncated }>`; `limit`
245
+ ≤ 100. Each entry is `{ subject, displayName, score, source, updatedAt }`, where `source` is
246
+ `'session'` (client-claimed) or `'room'` (written by the authoritative room).
247
+ - Both need a shell — in preview mode they reject rather than fake a board.
248
+
249
+ ### Achievements
250
+
251
+ `Helix.achievements` is a **read-only** view of the achievements registered to **this world** and
252
+ whether the viewer has earned them — the world id comes from the shell, so a world can never
253
+ enumerate the viewer's earns anywhere else. Awarding is server-side only: write-time criteria, or
254
+ the multiplayer room's `awardAchievement` rule. There is no award/claim method here by design.
255
+
256
+ ```ts
257
+ const { achievements, total, earned } = await Helix.achievements.list();
258
+ setProgressLabel(`${earned}/${total} earned here`);
259
+ for (const a of achievements) addBadge(a.name, a.iconUrl, a.earned, a.points);
260
+
261
+ const mine = await Helix.achievements.mine(); // the earned-only subset for this world
262
+ ```
263
+
264
+ - `Helix.achievements.list()` → `Promise<{ achievements, total, earned }>` — every achievement of
265
+ this world; `total` is the world's count, `earned` how many the viewer holds (0 when signed out).
266
+ - `Helix.achievements.mine()` → `Promise<{ achievements }>` — the earned ones only. Empty for a
267
+ signed-out player (they have earned nothing).
268
+ - Each row is `{ id, key, name, description, points, hidden, earned, rarityTier, earnPct, iconUrl }`.
269
+ A **hidden** achievement the viewer has **not** earned arrives **redacted** — the shell replaces
270
+ `name`/`description` with placeholders and blanks `key`/`iconUrl`, so neither a hidden name nor the
271
+ slug that spells it reaches world code. Identify such a row by `id`.
272
+ - Preview mode (no shell) resolves neutral empties rather than rejecting — this is display data and
273
+ must never break the world loop. A real backend failure still rejects (see below).
274
+
275
+ **Failures carry a code.** A rejected call throws a `HelixRequestError` whose `code` classifies it,
276
+ so a world branches on the code rather than matching error prose: `version-conflict` (stale
277
+ `expectedVersion` — re-read and re-apply), `rate-limited`, `session-foreign-key` (another player's
278
+ key), `session-sub-key` (a key under your own — use the one document), `session-server-key`,
279
+ `platform-reserved` (`helix:*`), `prefix-reserved` (`mail:*`, `mp:world`, `leaderboard:*`),
280
+ `counter-server-only`, `leaderboard-self-only`. `code` is `undefined` when the shell is older than
281
+ the code it would have sent, or the failure has no classification.
282
+
283
+ ### Multiplayer rooms and room types
284
+
285
+ ```ts
286
+ import { Helix, HelixRoomJoinError } from '@hypersoniclabs/helix-sdk';
287
+
288
+ // The world's default room. No options, no request body — unchanged from every earlier SDK.
289
+ let room = await Helix.multiplayer.joinRoom();
290
+
291
+ // The room hands this player a ticket when one of its rules opens a ticketed room for them.
292
+ room.onTicket(async (ticket) => {
293
+ // ticket: { roomType, ticketId, instanceId, expiresAt }
294
+ // expiresAt (Unix epoch ms) is when the TICKET stops being redeemable, not when the room ends.
295
+ try {
296
+ room = await Helix.multiplayer.switchRoom({ ticket: ticket.ticketId });
297
+ } catch (e) {
298
+ // The old room was left before the join was tried, so you are in no room now (see the table below).
299
+ // joinRoom() returns to the match if it is still reachable, otherwise to the default room.
300
+ if (e instanceof HelixRoomJoinError) console.warn('could not enter the match:', e.code);
301
+ room = await Helix.multiplayer.joinRoom();
302
+ }
303
+ });
304
+ ```
305
+
306
+ A world declares extra **room types** in its manifest (`multiplayer.roomTypes`). The top-level
307
+ `multiplayer` block stays the default type. An `open` type is joined by name; a `ticketed` type is
308
+ entered only by redeeming a ticket the platform issued to that player.
309
+
310
+ - `Helix.multiplayer.joinRoom(worldId?, options?)` → `Promise<HelixRoom>`. `options.roomType` joins an
311
+ open type and `options.ticket` redeems a ticket; pass one or neither, never both. With neither the
312
+ join is the default room and nothing about it changed: no request body, the same join options.
313
+ - `room.roomType` is the room's type (`null` for the default room) and `room.instanceKey` the ticketed
314
+ instance id (`null` otherwise).
315
+ - `room.onTicket(cb)` → unsubscribe. Tickets are not replayed, so subscribe right after joining.
316
+ Redeem a ticket before `ticket.expiresAt` (a few minutes); after that the redeem fails with
317
+ `ticket-invalid`. The room it leads to may run much longer than the ticket lasts.
318
+ - `Helix.multiplayer.switchRoom(target, options?)` → `Promise<HelixRoom>`. `target` is `{ ticket }`, or
319
+ `{ roomType?, preferInstanceId? }` (omit `roomType` for the default room). It leaves the current room
320
+ with a consented close, then joins the target. `preferInstanceId` is tried first and is not strict: if
321
+ that room is gone or full, the hop matchmakes into the same type instead. `options` takes the same
322
+ per-join fields as `joinRoom` (`uploadHz`, `apiBaseUrl`, `reservationPath`).
323
+
324
+ **What a failed hop costs.** Every `switchRoom` rejection is a `HelixRoomJoinError`. The target and
325
+ the session are checked first, so `left`, `invalid-target`, `not-ready`, `switch-in-progress` and
326
+ `join-in-progress` reject with you still in the room you were in. Any other code means the old room
327
+ has already been left and you are in no room. `Helix.multiplayer.currentRoomId()` tells you which.
328
+ `joinRoom` throws the same error type when the platform refuses the request. Branch on `error.code`:
329
+
330
+ | `code` | Meaning | Still in the old room? |
331
+ | --- | --- | --- |
332
+ | `left` | The player has left this world (`Helix.hasLeft()`). Checked before anything else; nothing is sent. Also thrown by `joinRoom`. | the call changed nothing (the leave itself already left the room) |
333
+ | `invalid-target` | Both `roomType` and `ticket`, or an empty id. | yes |
334
+ | `not-ready` | No `Helix.init()`, no session, no world id, or no API base. | yes |
335
+ | `switch-in-progress` | A `switchRoom` is still running (also thrown by `joinRoom` during a hop). | yes |
336
+ | `join-in-progress` | A `joinRoom` is still running: `switchRoom` was called under it, or a second `joinRoom` was. One join runs at a time. | yes |
337
+ | `unknown-room-type` | The active build declares no such type, or room types are off for the world. | no |
338
+ | `ticket-required` | The type is ticketed; it needs a ticket. | no |
339
+ | `ticket-invalid` | The ticket is unknown, expired, already used, or was issued to another player. | no |
340
+ | `instance-closed` | The ticketed room has closed: the match is over. Not retried. | no |
341
+ | `rejoin-failed` | Resuming a ticketed room failed. See "Reloads" below for what is kept. | no |
342
+ | `room-type-unavailable` | The platform reserved a default room for a typed request (it predates room types). | no |
343
+ | `cancelled` | `Helix.multiplayer.leave()` (or the shell's leave) arrived during the hop. Also thrown by a `joinRoom` that was left while joining. Any seat already taken was released. | no |
344
+ | `join-failed` | Anything else. `error.cause` holds the original failure when there is one. | no |
345
+
346
+ The codes come from the backend's own error `code`, not from the HTTP status, so an unrelated 404 is
347
+ `join-failed` and not `ticket-invalid`.
348
+
349
+ **Which errors are `HelixRoomJoinError`.** Every `switchRoom` rejection is one. From `joinRoom`, these
350
+ are:
351
+
352
+ - the platform refusing the join request (any non-2xx answer from the join endpoint). This used to be a
353
+ plain `Error`; the message is unchanged, `error.name` is now `HelixRoomJoinError`, and `error.code` /
354
+ `error.status` are available. This is the only change to a default join.
355
+ - `left`, `invalid-target`, `room-type-unavailable` and `switch-in-progress`;
356
+ - a failed resume of a ticketed room (`instance-closed`, `rejoin-failed`).
357
+
358
+ These `joinRoom` failures are still a plain `Error`, as before:
359
+
360
+ - a refused strict `?instance=` join. Its message is `could not join instance <id> — it may be full,
361
+ locked, or no longer exist (<server's reason>)`, and the shell is told through
362
+ `helix:multiplayer-join-error`;
363
+ - a missing precondition (no `Helix.init()`, no session, no world id, no API base, already in a room, a
364
+ bad `reservationPath`);
365
+ - the room connection itself failing after the platform reserved a seat (the Colyseus error is thrown
366
+ as is).
367
+
368
+ **Do not auto-rejoin on a leave you caused.** `room.onLeave((code, reason) => …)` now passes a
369
+ `reason`:
370
+
371
+ | `reason` | Meaning |
372
+ | --- | --- |
373
+ | `'switch'` | You called `switchRoom`. The hop is already joining the next room; do nothing. |
374
+ | `'leave'` | You called `room.leave()`, or the player used the shell's Exit. |
375
+ | `'dropped'` | Kicked, the room closed, or the connection was lost for good. Rejoin here if you want to. |
376
+
377
+ A world that rejoins on every `onLeave` would fight its own hop. `joinRoom()` during a hop is refused
378
+ with `switch-in-progress` and opens no second connection, but check `reason` rather than rely on that.
379
+
380
+ **When the player leaves the world.** The shell's Exit button and the browser's Back off the play page
381
+ (and, for some worlds, the play page being unloaded) reach the world as one message. The SDK then leaves
382
+ the room and voice and stops matchmaking and parties. A room handle only hears about this when there is
383
+ a room: `onLeave` with reason `'leave'`, or `cancelled` for a join in flight. A world that runs its own
384
+ room lifecycle can be between rooms at that moment, in a local bot match or waiting before its own next
385
+ rejoin attempt, and would then rejoin a room after the player has gone. The SDK covers that case
386
+ itself:
387
+
388
+ - `Helix.hasLeft()` turns `true` and every `Helix.onLeave` subscriber is called once, synchronously.
389
+ The subscribers are a snapshot taken when the leave arrives: unsubscribing another subscriber from
390
+ inside a callback does not stop it being called for this leave.
391
+ - From then on `joinRoom()` and `switchRoom()` reject with `left` before doing anything: no request,
392
+ no connection. That holds whether or not a room was held when the leave came.
393
+ - It lasts for the rest of the world document. The shell never re-enters a world in the same document:
394
+ entering again loads a new iframe, so a new SDK and a new handshake, and `hasLeft()` starts at `false`
395
+ there. The one exception is the play page coming back from the browser's back/forward cache, which
396
+ shows the same document again without a handshake. Then `hasLeft()` is `false` again and rooms can be
397
+ joined. Matchmaking and parties are not restarted by that; they stay stopped until a new session.
398
+ - Only the shell that initialised the world can end it. A leave message that arrives before the
399
+ handshake, or from another origin, is ignored for this purpose.
400
+
401
+ ```ts
402
+ Helix.onLeave(() => game.stopEverything()); // the player is going; show nothing new
403
+
404
+ async function rejoinLater() {
405
+ await wait(backoffMs);
406
+ if (Helix.hasLeft()) return; // the player left while we waited
407
+ try {
408
+ room = await Helix.multiplayer.joinRoom();
409
+ } catch (e) {
410
+ // `left` if the leave came first, `cancelled` if it came while this join was in flight.
411
+ if (Helix.hasLeft()) return;
412
+ throw e;
413
+ }
414
+ }
415
+ ```
416
+
417
+ A world that never calls these sees no difference until the player leaves, and the SDK adds nothing for
418
+ it: no request, no timer, no listener. After a leave it holds one `pageshow` listener, for the
419
+ back/forward-cache case above.
420
+
421
+ `left` is a new member of the `HelixRoomJoinErrorCode` union. TypeScript code that switches over
422
+ `error.code` and ends in an exhaustive `never` check stops compiling against this version until it
423
+ handles `left`. That is a compile-time break only; nothing changes at run time for such code until a
424
+ leave actually happens.
425
+
426
+ **`leave()` cancels a join or hop in flight.** Three things follow from that:
427
+
428
+ - Do not call `Helix.multiplayer.leave()` from the old room's `onLeave` when `reason` is `'switch'`.
429
+ It cancels the hop you just started: `switchRoom` rejects with `cancelled` and you end in no room.
430
+ - `joinRoom(); leave(); joinRoom()` without awaiting ends in no room. The first join rejects with
431
+ `cancelled`, and the second is refused with `join-in-progress` because the first has not finished
432
+ winding down. Await `leave()` before joining again.
433
+ - `leave()` waits for the cancelled call to finish, but for no longer than 3 seconds
434
+ (`ROOM_LEAVE_TIMEOUT_MS`). If the join's request or the room handshake has still not answered by
435
+ then, the SDK gives up on the call: `joinRoom` / `switchRoom` rejects with `cancelled` at that
436
+ moment and `leave()` resolves with you in no room. You can call `joinRoom()` again as soon as
437
+ `leave()` has resolved; it is no longer refused with `join-in-progress` while the old request hangs.
438
+ The abandoned request is not aborted on the network. Its answer is ignored when it arrives, and a
439
+ seat a late handshake delivers is released at once and never becomes your room.
440
+ - A `leave()` that cancels a join into a ticketed room also forgets that room. The SDK drops its
441
+ record of the instance when `leave()` is called, and the cancelled join cannot write it back, so
442
+ a page reload followed by a plain `joinRoom()` makes an ordinary join. It does not rejoin the
443
+ match you left.
444
+
445
+ `cancelled` is a new member of the `HelixRoomJoinErrorCode` union. A `switch` over `error.code` that
446
+ ends in an exhaustive `never` check needs a case for it before it compiles against this version.
447
+
448
+ **A handle belongs to one room.** After a hop, or after you leave, the old handle is stale and cannot
449
+ act on the room that came after it. Its `leave()` resolves and does nothing. `sendState`, `sendAction`,
450
+ entity uploads and module/vehicle actions do nothing (the boolean ones return `false`), and
451
+ `requestDistributionCapability` and the physics-group calls reject. Its subscriptions stop firing and
452
+ new ones register nothing. `onLeave` fires once. Its ids and `state` / `vars` keep the last values that
453
+ room replicated. Use the handle `joinRoom` or `switchRoom` returned most recently.
454
+
455
+ **A leave cannot hang on a dead connection.** This holds for `room.leave()`,
456
+ `Helix.multiplayer.leave()`, the shell's Exit and a hop alike. On a healthy connection nothing changed:
457
+ the leave resolves when the server confirms it. If the room does not confirm within 3 seconds
458
+ (`ROOM_LEAVE_TIMEOUT_MS`), for example because the connection is dead but has not noticed, the SDK
459
+ detaches the room locally and resolves; a hop then carries on with the join. A connection already known
460
+ to be closed is detached at once. A room the SDK has left never reconnects afterwards: its
461
+ auto-reconnection is switched off, so it cannot hold a second seat behind your back.
462
+
463
+ **Reconnecting after a drop follows the room's grace.** When the connection drops, the room holds
464
+ the seat for 20 seconds (`ROOM_RECONNECT_GRACE_MS`, the room server's reconnection grace) and the SDK
465
+ reconnects on its own: `room.onDrop` fires, then `room.onReconnect` when the same seat is back. The
466
+ 20 seconds start when the SERVER notices the drop. In the common drops the client notices first (a
467
+ wifi switch, a network change, the browser going offline) and the server only on its ping timeout,
468
+ up to 9 seconds later (`ROOM_SERVER_DROP_DETECTION_MS`: a ping every 3 s, the connection cut after 2
469
+ unanswered). So a seat can be resumed until about 29 seconds after the drop the client saw
470
+ (`ROOM_RECONNECT_WINDOW_MS`). Two timings changed in this version, on every room including the
471
+ default one:
472
+
473
+ - A drop in the first 5 seconds after the join is reconnected too. Before, Colyseus did not try at
474
+ all in that window: `onLeave` fired at once with `'dropped'` while the room still held the seat.
475
+ - While the network stays down, the SDK stops trying once that window has passed. Before, Colyseus
476
+ kept trying for about a minute (15 tries, up to 5 seconds apart), long after the seat was gone.
477
+ Retries keep Colyseus's own backoff inside the window; none is started after it, and an attempt
478
+ still connecting 2 seconds after it (`ROOM_RECONNECT_ATTEMPT_ALLOWANCE_MS`) is closed. The give-up
479
+ is `room.onLeave(4003, 'dropped')`, between 29 and about 31 seconds after the drop. The window is
480
+ measured on a monotonic clock, so changing the device's clock does not move it.
481
+
482
+ When the server is reachable and no longer holds the seat, it refuses the reconnection with 4003, and
483
+ `room.onLeave(4003, 'dropped')` fires at once, as before. Either way that is the moment to take a new
484
+ seat with `joinRoom()` (or a ticketed room's rejoin, which `joinRoom()` does for you). Each new drop
485
+ after a successful reconnect gets a fresh window. Nothing else about the default room changed.
486
+
487
+ **`?instance=` and room types.** The play URL's `?instance=` names a default-type room. A first default
488
+ `joinRoom()` still joins exactly that room or fails loudly, as before; the error now carries the
489
+ server's own reason instead of a guess that the room is full. A typed or ticket join ignores
490
+ it. A `switchRoom` back to the default type with no `preferInstanceId` uses it as the preferred room,
491
+ with the matchmaker fallback.
492
+
493
+ **Reloads resume the room you were in.** Each room type has its own reconnect slot in
494
+ `sessionStorage`. After a reload, a plain `joinRoom()` first resumes the typed room the tab was in, and
495
+ only then the default room, so a reload during a match returns to the match even though the URL still
496
+ names the lobby. Read `room.roomType` to see where you landed. Four details:
497
+
498
+ - Everything remembered is bound to the player it was remembered for (the World session's issuer,
499
+ subject, world and guest flag). After a sign-in, a sign-out or an account switch, the next
500
+ `joinRoom()` is an ordinary join: the other player's seat, typed room and ticketed instance are
501
+ forgotten, never resumed. A token refresh for the same player keeps them.
502
+
503
+ - If the player picks a different server in the shell (a different `?instance=`), that choice wins: the
504
+ typed room is forgotten and the default join to the new server happens.
505
+ - A ticketed room is remembered from the moment its ticket is redeemed. If the seat is gone, or the
506
+ connection failed after the ticket was spent, `joinRoom()` asks the platform for a fresh ticket to
507
+ the same instance. When the platform says the instance is closed (`instance-closed`) or is not yours
508
+ (`rejoin-failed`, HTTP 403 or 404), it is forgotten and the next `joinRoom()` is an ordinary join.
509
+ On a failure that says nothing about the match (`rejoin-failed` with `error.status` `null` for no
510
+ answer, 5xx, 429, or 401 while the session refreshes) it is kept, and the next `joinRoom()` asks again.
511
+ - To stop returning to a remembered match, hop elsewhere: `switchRoom({})` goes to the default room and
512
+ forgets it.
513
+
514
+ **Voice follows a hop.** If `Helix.voice` was joined to the room, `switchRoom` leaves it before the hop
515
+ and joins the new room's voice with the same push-to-talk key; the channel, mic mode and mutes carry
516
+ over. The new room handle is returned as soon as the room is joined. Voice re-joins in the background
517
+ and a voice failure is logged, not thrown. A `Helix.voice.join()` still connecting when the hop starts
518
+ is cancelled (it resolves `false`) and re-targeted at the new room. If the hop fails, voice stays
519
+ left, because there is no room to pair it with; call `Helix.voice.join()` after your next join. Voice
520
+ joined with an explicit `roomId` is left alone.
521
+
522
+ **What the shell is told.** The room status the SDK publishes to the shell
523
+ (`helix:multiplayer-state`) carries `roomType` for a typed room and `ticketed: true` for a ticketed
524
+ one. Both are absent for the default room, so that message is unchanged for worlds without room
525
+ types. The shell uses them to avoid offering a private ticketed room as a public join target. During
526
+ a hop the SDK publishes `null` and then the new room's state.
527
+
528
+ **Local dev.** `helix dev` has no room server, so `joinRoom()` does not work there. The dev shell can
529
+ answer the join table and mint a ticket for tests and the debug menu (`roomTypes` option,
530
+ `simulateRoomJoin`, `issueRoomTicket`, `rejoinRoomInstance`, `closeRoomInstance`). Refusals carry the
531
+ backend's `{ statusCode, code, message }` body. Real typed joins need the dev-stack.
532
+
533
+ ### Matchmaking and parties
534
+
535
+ A world declares **queues** in its manifest (`matchmaking.queues`). Each queue names a ticketed room
536
+ type and the team layout. A player enqueues, the platform forms the match and opens the room, and
537
+ every matched player gets a room ticket to redeem with `switchRoom`.
538
+
539
+ ```ts
540
+ import { Helix, HelixMatchmakingError } from '@hypersoniclabs/helix-sdk';
541
+
542
+ let room = await Helix.multiplayer.joinRoom(); // the lobby (default room)
543
+
544
+ // Subscribe once, at startup. This also picks up a ticket that survived a reload.
545
+ Helix.matchmaking.onStatus((s) => {
546
+ // s: { status: 'none' | 'waiting' | 'matched', queueId?, waiting?: { players, needed }, match?, reason? }
547
+ ui.showQueue(s.status === 'waiting' ? s.waiting : null);
548
+ if (s.reason === 'heartbeat-lost' || s.reason === 'heartbeat-lapsed') ui.toast('Lost your place in the queue. Try again.');
549
+ if (s.reason === 'member-absent') ui.toast('A party member went away. Queue again when they are back.');
550
+ });
551
+ Helix.matchmaking.onMatch(async (match) => {
552
+ // match: { ticketId, instanceId, roomType, expiresAt } — redeem before expiresAt (Unix epoch ms).
553
+ try {
554
+ room = await Helix.multiplayer.switchRoom({ ticket: match.ticketId });
555
+ } catch {
556
+ room = await Helix.multiplayer.joinRoom(); // the hop failed after leaving the lobby: go back
557
+ }
558
+ });
559
+
560
+ async function play() {
561
+ try {
562
+ await Helix.matchmaking.enqueue('duel'); // → { status: 'waiting', queueId: 'duel' }
563
+ } catch (e) {
564
+ if (e instanceof HelixMatchmakingError) ui.toast(e.code); // 'guests-cannot-queue', 'already-queued', …
565
+ }
566
+ }
567
+
568
+ async function matchOver() {
569
+ room = await Helix.multiplayer.switchRoom({}); // back to the default room
570
+ }
571
+ ```
572
+
573
+ - `Helix.matchmaking.enqueue(queueId)` → `Promise<QueueStatus>`. In a party only the leader queues,
574
+ and the whole party is queued together. `enqueue` and `cancel` calls run one at a time, in the order
575
+ you made them. While a match still stands unredeemed (yours or a party member's) it rejects with
576
+ `already-matched`, exactly as a late `cancel()` does: `error.match` is the match, the status is
577
+ `matched` and `onMatch` fires if you had not been told yet. Redeem it or let it expire first. If
578
+ `error.match` is `null`, the pending match is another party member's (`error.memberUserId`): someone
579
+ in your party still has a match to redeem. Your own status does not change; try again once they have joined it or it
580
+ has expired.
581
+ - `Helix.matchmaking.cancel()` → `Promise<void>`. Resolves when a waiting ticket was cancelled or there
582
+ was none. A party member cancelling cancels the party's ticket. If the ticket has already matched,
583
+ it rejects with `already-matched`: `error.match` is the match, the status is `matched` and `onMatch`
584
+ fires, so redeem it. If the request gets no usable answer, the SDK asks the platform what happened
585
+ before rejecting, so a match that formed in the meantime is still delivered.
586
+ - `Helix.matchmaking.status()` → `Promise<QueueStatus>`. Asks the platform now. What it finds is
587
+ handled like a poll result: the listeners fire if it is news.
588
+ - `Helix.matchmaking.onStatus(cb)` → unsubscribe. Fires when the status changes, not on every poll.
589
+ `waiting.players` counts the players currently eligible to be matched (every member of their party
590
+ polled recently), so it can be lower than the number who pressed the button.
591
+ - **Why it ended.** A `none` carries a `reason` when one is known, and `onStatus` fires once per
592
+ ending. The platform reports how your ticket in this world closed: `cancelled`, `timeout` (the
593
+ queue's waiting limit), `heartbeat-lapsed` (nobody on the ticket polled for 15 s), `member-absent`
594
+ (one party member did not poll for 60 s), `party-changed`, `build-changed`, `queue-removed`, or
595
+ `replaced` (you queued in another world; a player has one waiting ticket), or `match-expired` (the
596
+ match's room ticket ran out, or its room closed, before you redeemed it). A reason this SDK does
597
+ not know is `ended`. `serverReason` always has the platform's own word. When the SDK cannot ask, it
598
+ concludes one itself: `heartbeat-lost`, `match-expired`, `refused` (the platform turned the poll
599
+ down for good), `session-changed` or `left`. After a reload, the first check tells you once how
600
+ the ticket you had ended. A `none` after a match was redeemed has no reason.
601
+ - `Helix.matchmaking.onMatch(cb)` → unsubscribe. Fires once per match (per room `ticketId`), whether a
602
+ poll, a `status()` call, a late `cancel()` or the first check after a reload found it. A match found
603
+ before any listener existed is handed to the first one, unless it has expired or the status has gone
604
+ back to `none`. Nothing joins the room for you: call `switchRoom`.
605
+
606
+ **Polling and the heartbeat.** There is no push in this version. While a ticket is `waiting` or
607
+ `matched` the SDK asks the platform for its status every 3 seconds, and stops when the status is
608
+ `none`. For a waiting ticket that request is also the heartbeat: the platform cancels a waiting
609
+ ticket that was not polled for 15 seconds. So:
610
+
611
+ - The poll keeps running while the tab is hidden. Browsers slow a hidden page's timers (to once a
612
+ minute after about five minutes), so the SDK runs the 3 second tick in a small dedicated worker,
613
+ which is not slowed. If the page's CSP forbids `blob:` workers it falls back to an ordinary timer,
614
+ and a tab hidden for several minutes can then lose its place.
615
+ - The SDK polls at once when the tab becomes visible, the page is restored, or the network returns.
616
+ - A tab the browser fully suspends or discards (mobile background, a sleeping laptop, tab
617
+ discarding) cannot poll at all. After 15 seconds the ticket is gone and `onStatus` reports `none`
618
+ when the tab wakes. Enqueue again.
619
+ - A request with no answer after 8 seconds is abandoned, so one hung request cannot stop the loop.
620
+ The status poll itself is given up after 5 seconds, so a single hung poll leaves at most 9 seconds
621
+ without a heartbeat.
622
+ - If `enqueue()` gets no usable answer (a timeout, a lost connection, a 5xx) it still rejects, but the
623
+ SDK then asks the platform whether the ticket exists. If it does, `onStatus` reports `waiting` and
624
+ the heartbeat starts, so a ticket the platform did create is not left to lapse.
625
+ - An answer that was already on its way when `enqueue()` or `cancel()` finished never overrides their
626
+ result.
627
+ - A poll refused for good (`missing-permission`, `unavailable`, a guest session) ends the queue at
628
+ once: `none` with `reason: 'refused'`.
629
+ - A failed poll (no network, a 5xx, a 429, a 401 while the shell refreshes the session) does not end
630
+ the queue at once. The SDK retries with a growing gap. When nothing has got through for 15 seconds
631
+ the platform has cancelled the ticket, so `onStatus` reports `none` with `reason: 'heartbeat-lost'`
632
+ at the 15 second mark and polling stops. The SDK has no way to refresh the session itself; it uses the new token as soon
633
+ as the shell sends one.
634
+ - Time the page spent asleep (a suspended laptop, a frozen tab) is not counted as failed polls. When
635
+ the page runs again after 6 seconds or more of not running, the SDK polls at once and reports what
636
+ the platform answers, whether the ticket survived or not. `heartbeat-lost` is reported only if
637
+ nothing gets through for 15 seconds after waking.
638
+ - That allowance is for one sleep, not for every one. If the page wakes, polls, gets no answer, and
639
+ then goes 6 seconds or more without running again, the 15 seconds keep counting from the first
640
+ wake. The next wake still polls and an answer is still believed. If that poll fails too, or two
641
+ wakes in a row have sent a poll that was never answered, the status becomes `none` with
642
+ `reason: 'heartbeat-lost'`. This is what a hidden tab does when the page cannot start the
643
+ heartbeat worker (a CSP without `worker-src blob:`), the browser lets its timers run about once a
644
+ minute, and the network is down: it reports the lost ticket on the second or third run instead
645
+ of showing `waiting` until the network returns.
646
+ - A matched ticket is polled until its room ticket expires. After one last poll the status becomes
647
+ `none` with `reason: 'match-expired'`.
648
+ - **Expiry is judged by the platform's clock, not the device's.** A match's `expiresAt` (and an
649
+ invite's) is the platform's time. A device clock running fast by more than a ticket's life used to
650
+ skip every match, and one running slow was handed tickets already dead. The SDK now learns the
651
+ platform's time from what it already receives: the state of a joined room (`serverTimeMs`, stamped
652
+ by the room server every tick) and, when the browser lets the page read it, the `Date` header of the
653
+ platform's answers. It keeps the offset after a room is left, so a match found later is still
654
+ judged right, but when both are known the source heard from most recently decides. One stray answer
655
+ cannot move it: the estimate is the median of the recent samples and is used only while most of
656
+ them agree. With nothing to go by (no room joined yet and the header not
657
+ readable) the device clock is used, as before. A cross-origin world can read `Date` only when the
658
+ platform API lists it in `Access-Control-Expose-Headers`, so for now a world that has never joined
659
+ a room is judged by the device clock. The platform has the last word either way: a dead ticket is
660
+ refused at redeem.
661
+ - After a reload the SDK has no ticket in memory. The first `onStatus`, `onMatch` or `status()` call
662
+ asks the platform once and resumes polling if a ticket is still waiting or matched. Subscribing
663
+ before `Helix.init()` has resolved works: the check runs when it does.
664
+ - When the session ends or another player signs in, subscribers get `none` (`session-changed`) and
665
+ the new session's ticket is looked up.
666
+ - On the shell's leave message subscribers get `none` (`left`), polling stops and later calls reject
667
+ with `not-ready`. Polling also stops on page teardown; a page restored from the back/forward cache
668
+ resumes. A world that never calls `Helix.matchmaking` or `Helix.party` makes no request and holds
669
+ no timer. A world that listens to matchmaking pays for one `GET /parties/current` every 5
670
+ seconds while the tab is visible (see "Queueing as a party").
671
+
672
+ **Queueing as a party.** The platform keeps a heartbeat for every member, not only the leader. A
673
+ party's ticket can only be matched while every member has polled the queue status in this world
674
+ within the last 15 seconds, and it is cancelled when any member has not polled for 60 seconds. Only
675
+ the leader calls `enqueue`, so the other members' SDKs find the ticket themselves:
676
+
677
+ - Every party member's world must have subscribed to `Helix.matchmaking.onMatch` (or `onStatus`).
678
+ Do it at startup, as in the example above. A member whose world never subscribes makes the party
679
+ unmatchable.
680
+ - **What a listener costs.** While a world has a matchmaking listener the SDK sends one
681
+ `GET /parties/current` every 5 seconds, whether or not the world uses `Helix.party`. That is how
682
+ it learns the player joined a party; `Helix.party.accept()` and `join()` tell it at once. While the
683
+ tab is hidden this poll rests, unless the player is in a party of two or more, has a waiting
684
+ ticket, or the world subscribed to party events itself. It resumes when the tab is visible.
685
+ - While the player is in a party of two or more and is not queued, the SDK asks for the queue status
686
+ every 5 seconds. When the leader queues, the member's `onStatus` reports `waiting` and the SDK
687
+ switches to the 3 second heartbeat. `onMatch` then fires for every member.
688
+ - A solo player, or a party of one, never makes those idle requests.
689
+ - A member whose tab is suspended or closed stops polling. The party cannot be matched until they
690
+ return, and after 60 seconds the ticket is cancelled for everyone.
691
+ - The idle requests stop when the last matchmaking listener unsubscribes or the party drops below
692
+ two members.
693
+
694
+ **Parties.** A party is a platform-level group of accounts with one leader. It is not tied to a
695
+ room or a world. There is no shell UI for it in this version; the world draws its own. The world's
696
+ manifest needs the `multiplayer` permission: without it every matchmaking and party call is refused
697
+ with `missing-permission`.
698
+
699
+ ```ts
700
+ import { Helix, HelixPartyError } from '@hypersoniclabs/helix-sdk';
701
+
702
+ const { party, invites } = await Helix.party.get(); // party is null when you are in none
703
+ Helix.party.onChange((state) => ui.showParty(state.party));
704
+ Helix.party.onInvite(async (invite) => {
705
+ // invite: { id, partyId, from: { userId, displayName }, expiresAt }
706
+ if (await ui.confirm(`${invite.from.displayName} invited you`)) await Helix.party.accept(invite.id);
707
+ else await Helix.party.decline(invite.id);
708
+ });
709
+
710
+ Helix.party.onError((e) => ui.hidePartyPanel(e.code)); // the background poll was refused and stopped
711
+
712
+ // Grouping up with anyone: the leader shares a code, the others type it.
713
+ const { code } = await Helix.party.createCode(); // e.g. show "Party code: 7KQ2MX9P"
714
+ await Helix.party.join(typedCode); // on the other players' side
715
+
716
+ await Helix.party.invite(userId); // an accepted friend (see below for anyone else)
717
+ ```
718
+
719
+ **Codes are the default way for strangers to party up.** `invite()` reaches an accepted friend. A
720
+ non-friend can be invited only if they are in this world and have public presence with activity
721
+ sharing on. The account default is friends-only, so for most non-friends `invite()` fails with
722
+ `cannot-invite`. A code (8 characters) has no such limit.
723
+
724
+ - `Helix.party.get()` → `Promise<PartyState>`: `{ party: { id, leaderId, maxSize, members } | null, invites }`.
725
+ - `Helix.party.onChange(cb)` / `Helix.party.onInvite(cb)` → unsubscribe. The platform is polled every
726
+ 5 seconds only while at least one of them is subscribed. `onChange` fires when the state differs
727
+ from the previous answer; the first answer after subscribing is the baseline, so read the starting
728
+ state with `get()`. When the last subscriber leaves, the baseline is forgotten. `onInvite` fires
729
+ once per invite id, including invites already pending, always from a fresh answer and never for an
730
+ expired invite. If the session changes, `onChange` reports no party and the new session is polled.
731
+ - `Helix.party.onError(cb)` → unsubscribe. The background poll retries a failure with a growing gap
732
+ (up to 30 seconds) and says nothing: no answer, a 5xx, a 429, a 401 from an expired token, and any
733
+ other refusal (a 403 or 404 with no code, a code this SDK does not know). One such answer is not
734
+ taken as the next one. A session refresh from the shell retries at once. Only a final answer stops
735
+ the poll: `missing-permission`, `unavailable` (parties switched off) or a guest session. Then `cb`
736
+ gets the `HelixPartyError` once, and a listener added later gets it too. The poll starts again by
737
+ itself when the shell sends a new or refreshed session, and as soon as one of your own party calls
738
+ (`get()`, `invite()`, …) is answered successfully, so a world that asks again after a deploy turned
739
+ parties off for a moment gets its updates back. Errors from calls you make yourself reject those
740
+ calls and are not sent here. (Before this version any 4xx stopped the poll, and only a new session
741
+ started it again.)
742
+ - `Helix.party.createCode()` → `Promise<{ code, expiresAt }>`. Leader only. Creates a party of one
743
+ if you have none. The leader also sees the code as `party.code` in `get()` and `onChange`; other
744
+ members do not.
745
+ - `Helix.party.revokeCode()` → `Promise<void>`. Leader only.
746
+ - `Helix.party.join(code)` → `Promise<Party>`. The code is trimmed and upper-cased before it is sent.
747
+ An empty code, one with a space in it or one longer than 64 characters is rejected locally with
748
+ `invalid-argument`.
749
+ - `Helix.party.invite(userId)` → `Promise<{ inviteId, expiresAt }>`. Creates the party if you have
750
+ none and makes you its leader. The recipient has to accept. Inviting someone who already has a
751
+ pending invite from your party returns that same invite.
752
+ - Sending an invite or creating a code puts you in a party of one. From a party of one, accepting an
753
+ invite or joining by code moves you into the new party. `already-in-party` only means you are in a
754
+ party of two or more: call `Helix.party.leave()` first.
755
+ - `Helix.party.accept(inviteId)` → `Promise<Party>`; `Helix.party.decline(inviteId)` → `Promise<void>`.
756
+ `decline` resolves even when the invite no longer exists.
757
+ - `Helix.party.leave()`, `Helix.party.kick(userId)` → `Promise<void>`; `Helix.party.promote(userId)` →
758
+ `Promise<Party>`. Kick and promote are leader only. When the leader leaves, the longest-standing
759
+ member becomes leader.
760
+ - A party change (someone joins, leaves or is kicked) cancels that party's waiting queue ticket.
761
+
762
+ **Errors.** Every rejection is a `HelixMatchmakingError` or a `HelixPartyError` with `code`,
763
+ `status` (the HTTP status, or `null` when nothing was sent or nothing answered) and `backendCode`
764
+ (the platform's own code, when it sent one).
765
+
766
+ | `code` | Thrown by | Meaning |
767
+ | --- | --- | --- |
768
+ | `unknown-queue` | matchmaking | The manifest declares no such queue. |
769
+ | `already-queued` | matchmaking | You already have a waiting ticket in this world. The call rejects; the SDK makes sure that ticket is polled and `onStatus` reports it. A ticket in another world is not an error: enqueueing here replaces it. |
770
+ | `already-matched` | matchmaking | A match already stands (`cancel()` was too late, or `enqueue()` while it is unredeemed). `error.match` is the match and `onMatch` fires. From `enqueue()` it can be `null`: a party member's match is pending, and `error.memberUserId` names them. |
771
+ | `not-party-leader` | both | Only the leader queues, invites, kicks and promotes. |
772
+ | `party-too-large` | matchmaking | The party does not fit one team of this queue. |
773
+ | `party-changed` | both | The party changed while the request ran. Nothing happened; call again. The SDK already retried twice. |
774
+ | `missing-permission` | both | The world's manifest lacks the `multiplayer` permission. |
775
+ | `guests-cannot-queue` | matchmaking | Guest session. Checked locally first, so no request is sent. |
776
+ | `guests-cannot-party` | party | Guest session. Checked locally first, so no request is sent. |
777
+ | `cannot-invite` | party | Not a friend, and not invitable as a stranger (that needs them in this world with public presence and activity sharing on), or a block applies. Use a code. |
778
+ | `party-full` | party | No room left, when inviting or accepting. |
779
+ | `too-many-invites` | party | The party has its limit of pending invites. |
780
+ | `already-in-party` | party | You are in a party of two or more. Leave it before accepting an invite or joining by code. |
781
+ | `code-not-found` | party | No party has that join code (mistyped, expired or revoked). |
782
+ | `not-in-party` | party | You are in no party (leave, kick, promote). |
783
+ | `unknown-party-member` | party | That player is not in your party (kick, promote). |
784
+ | `invite-not-found` / `invite-expired` | party | The invite is unknown, or it ran out. |
785
+ | `rate-limited` | both | Too many enqueues, invites or code attempts (any HTTP 429). |
786
+ | `unavailable` | both | The feature is not enabled on this platform. |
787
+ | `not-ready` | both | No `Helix.init()`, no session, no world id, no API base, or the world was left. Nothing was sent. |
788
+ | `invalid-argument` | both | An empty id. Nothing was sent. |
789
+ | `request-failed` | both | Anything else: no answer within 8 s, a 5xx, a 401 from an expired token, a 404 with no code, or a code this SDK does not know. |
790
+
791
+ **Local dev.** `helix dev` gives the SDK no API base, so these calls reject with `not-ready` there.
792
+ The dev shell answers the same routes for tests and the debug menu: pass `queues` (and the
793
+ `roomTypes` they point at), call `simulatePlatformRequest(method, path, body?)` for any of the
794
+ routes, and use `formMatch()` to play the matcher. It issues a room ticket from the simulated
795
+ room-types table, which `simulateRoomJoin({ ticket })` then redeems. Until it is redeemed, cancelling
796
+ or enqueueing answers 409 `already-matched` with the match, as the backend does. `receivePartyInvite()`,
797
+ `acceptPartyInvite(inviteId)`, `openPartyCode()` and `usePartyCode(code)` play the other players. Refusals carry the backend's
798
+ `{ statusCode, code, message }` body.
53
799
 
54
800
  ## Protocol
55
801
 
@@ -58,6 +804,212 @@ shell) and is imported by both sides. Any breaking change must bump `PROTOCOL_VE
58
804
  `HelixSession` shape matches the backend's `InstantWorldSessionResponseDto`, so the shell forwards
59
805
  the backend response verbatim.
60
806
 
807
+ ## Engine-neutral runtime contract
808
+
809
+ The public Web surface is also captured in one generated, engine-neutral contract for Web, Unreal
810
+ and future bindings. Import the typed metadata without changing existing SDK behavior:
811
+
812
+ ```ts
813
+ import {
814
+ HELIX_RUNTIME_CONTRACT,
815
+ RUNTIME_CONTRACT_DIGEST,
816
+ getRuntimeMethod,
817
+ } from '@hypersoniclabs/helix-sdk/runtime-contract';
818
+
819
+ const purchase = getRuntimeMethod('marketplace.purchaseProduct');
820
+ // purchase.transportOwner === 'shell'
821
+ // purchase.authority === 'platform'
822
+ ```
823
+
824
+ The canonical source, generated C++ header, known-answer fixtures, authority rules and update
825
+ workflow are documented in [`docs/runtime-contract.md`](docs/runtime-contract.md). Audited broken
826
+ or authority-drifted calls are explicitly `unavailable` or `correction_required`; generators must
827
+ not reproduce their current false-success behavior.
828
+
829
+ ## Native avatar camera
830
+
831
+ `Helix.camera` carries two separate things. `capture`/`savePhoto` are the album pipeline: pixels a
832
+ world already rendered, on their way to the player's account, gated on the `camera.capture` manifest
833
+ capability. `getState`/`onStateChanged`/`capabilities`/`reportCapability`/`control` are the CAMERA —
834
+ the device the player's avatar carries, which HELIX OS opens.
835
+
836
+ HELIX OS owns the camera UI and pushes the whole state down; the runtime owns the rig and reports
837
+ what it can actually do back up.
838
+
839
+ ```ts
840
+ // The runtime declares its abilities at boot, and again whenever one is LOST.
841
+ Helix.camera.reportCapability({
842
+ photo: true, video: false, drone: false, twoHandPose: true,
843
+ focusPoint: true, exposureBias: false, worldAudio: false,
844
+ unavailableReason: 'this world ships photo only',
845
+ });
846
+
847
+ Helix.camera.onStateChanged((state) => {
848
+ // state.shutter.sequence is monotonic — fire on the CHANGE, never on a boolean.
849
+ applyCamera(state.spatial, state.zoom, state.filter);
850
+ });
851
+
852
+ // A world script driving the player's camera needs the `camera.control` capability, and a call the
853
+ // runtime already said it cannot serve fails locally with RUNTIME_CAPABILITY_UNAVAILABLE.
854
+ await Helix.camera.control({ spatial: 'selfie', zoom: 2.4, filter: 'vivid' });
855
+ ```
856
+
857
+ Reading the camera never requires a world manifest capability — it is an avatar ability, not
858
+ something the world asks for. The ownership split, the dynamic-capability model, the drone's
859
+ Phase-2 status, and the reasoning behind that permission boundary are in
860
+ [`docs/camera-contract.md`](docs/camera-contract.md).
861
+
862
+ ## Universal interaction action surface
863
+
864
+ `UniversalActionSurface` renders the shared `run`, `choice`, `number`, `text`, `point`, `asset`, and
865
+ `takeover` forms from a caller-scoped action snapshot. Labels, options, visibility, permissions,
866
+ and busy/occupied state come from authority; the snapshot is only a presentation cache, so every
867
+ invocation must still be re-authorized server-side.
868
+
869
+ ```ts
870
+ import {
871
+ UniversalActionSurface,
872
+ createActionSurfaceMode,
873
+ } from '@hypersoniclabs/helix-sdk';
874
+
875
+ const surface = new UniversalActionSurface({
876
+ host: document.querySelector('#ui')!,
877
+ hints: {
878
+ activeDevice: () => character.services.input.activeDevice(),
879
+ hint: (action) => character.services.input.hint(action),
880
+ },
881
+ onInvoke: ({ action, ...value }) => {
882
+ // Send action.call ?? action.id plus value to authority. Re-authorize there.
883
+ },
884
+ });
885
+
886
+ surface.setSnapshot(await actionsForNearbyItem());
887
+
888
+ // Proximity may show the offer without capturing movement. Push the engaged
889
+ // menu mode only after the player chooses to focus it.
890
+ await modeStack.push(createActionSurfaceMode({ surface }));
891
+ ```
892
+
893
+ The mode consumes only `move`, `primary`, and `cancel`; it never installs keyboard, gamepad, or
894
+ raw-touch bindings. A host whose input router has no change subscription calls `refreshHints()`
895
+ after an active-device or rebind change. Sustained number changes stream live while the native
896
+ range remains open, native text input preserves focus across authority refreshes, and choice/asset pickers keep the saved value visually distinct from
897
+ keyboard/gamepad focus. The port source is the frozen interactive-items prototype's
898
+ `src/client/ui.ts`; new development lives here.
899
+
900
+ `DeviceDefinitionV1.interactions` uses the same portable forms. A Device `text` control declares
901
+ its typed `stateKey` plus optional `placeholder`, `maxLength`, and Action Surface `inputMode`; the
902
+ enclosing interaction `label` is the player-facing prompt. Submitted text goes through normal
903
+ Device authority, which must validate it before writing state.
904
+
905
+ ## Vault assets
906
+
907
+ The Vault client lets a web world search and consume all 14 resource kinds
908
+ without coupling the SDK to Three.js or another renderer. Persist the returned
909
+ `{ assetId, version }` handle. Never persist `artifact.url`: it is a resolved
910
+ serving pointer, while the Vault ID and immutable integer version are the
911
+ durable identity.
912
+
913
+ ```ts
914
+ import { createVaultClient } from '@hypersoniclabs/helix-sdk';
915
+
916
+ const vault = createVaultClient({
917
+ apiBaseUrl: 'https://api.helixgame.com',
918
+ accessToken: () => Helix.getSessionToken(),
919
+ });
920
+
921
+ const result = await vault.search({
922
+ q: 'weathered stone',
923
+ kind: ['material', 'texture'],
924
+ performanceTier: 'mobile',
925
+ rank: 'performance',
926
+ });
927
+
928
+ const asset = await vault.resolve({
929
+ assetId: result.items[0].assetId,
930
+ version: result.items[0].currentVersion,
931
+ });
932
+ const plan = vault.createLoadPlan(asset);
933
+ const installed = await vault.install(asset.handle);
934
+
935
+ // `plan` is a typed handoff such as:
936
+ // - gltf (prop, character, animation, environment, terrain)
937
+ // - image (texture, decal)
938
+ // - audio
939
+ // - hdr-environment (HDR/EXR)
940
+ // - gaussian-splat (SPZ, with object/environment scope)
941
+ // - helix-descriptor (material, sky, terrain, VFX, scene)
942
+ //
943
+ // Pass `installed.primary.bytes` and `plan` to the world's chosen loader.
944
+ ```
945
+
946
+ Downloads follow the Vault's version-aware download route and verify the
947
+ server-provided SHA-256 by default when Web Crypto is available. A runtime
948
+ without Web Crypto may inject a portable `sha256` function. Related renditions
949
+ are resolved from asset detail and downloaded only when their roles are
950
+ explicitly requested:
951
+
952
+ ```ts
953
+ await vault.install(asset.handle, {
954
+ relatedRoles: ['ktx2-albedo', 'ktx2-normal'],
955
+ });
956
+ ```
957
+
958
+ The SDK deliberately does not report a client-side "usage" event. Vault usage
959
+ attribution is authoritative and derived when a world containing durable Vault
960
+ IDs is published. There is currently no separate install, usage-track, or
961
+ related-rendition API endpoint; `install()` is the local verified-download plus
962
+ loader-plan operation, and related artifacts come from asset detail.
963
+
964
+ ### Generate audio and consume the published Vault asset
965
+
966
+ Creator tools can use the SDK's typed Dreamer audio client with an authenticated
967
+ creator/client token. Sound effects, music, and text to speech all call the same
968
+ HELIX route; the SDK never calls ElevenLabs directly or handles a provider key.
969
+ Completed jobs are automatically published to Vault unless the creator has
970
+ explicitly opted out.
971
+
972
+ ```ts
973
+ import { createDreamerAudioClient } from '@hypersoniclabs/helix-sdk';
974
+
975
+ const audio = createDreamerAudioClient({
976
+ apiBaseUrl: 'https://api.helixgame.com',
977
+ accessToken: creatorToken,
978
+ });
979
+
980
+ const effect = await audio.generate({
981
+ audioMode: 'sound_effect',
982
+ prompt: 'heavy metal door slamming shut',
983
+ durationSeconds: 3,
984
+ promptInfluence: 0.4,
985
+ });
986
+
987
+ const music = await audio.generate({
988
+ audioMode: 'music',
989
+ prompt: 'hopeful orchestral exploration theme',
990
+ durationSeconds: 180,
991
+ forceInstrumental: true,
992
+ });
993
+
994
+ const voice = await audio.generateAndResolve({
995
+ audioMode: 'text_to_speech',
996
+ text: 'Welcome to HELIX.',
997
+ voiceId: '21m00Tcm4TlvDq8ikWAM',
998
+ languageCode: 'en',
999
+ voiceSettings: { stability: 0.5, speakerBoost: true },
1000
+ });
1001
+
1002
+ // The exact auto-published asset is now resolved through the normal Vault path.
1003
+ audioElement.src = voice.loadPlan.primary.url!;
1004
+ console.log(effect.vaultAssetId, music.vaultAssetId, voice.resolved.handle);
1005
+ ```
1006
+
1007
+ `generate()` polls for up to 30 minutes by default so long music generation has
1008
+ time to render, ingest, and publish. It returns measured `units`,
1009
+ `providerCostUsd`, server-stamped `billingEvidence`, and `vaultAssetId`.
1010
+ `generateAndResolve()` additionally requires default-on Vault publication and
1011
+ returns the renderer-neutral audio load plan for that same durable asset.
1012
+
61
1013
  ## Develop
62
1014
 
63
1015
  ```bash