@pollen-robotics/reachy-mini-sdk 1.7.3-main.b44388c

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 (85) hide show
  1. package/CHANGELOG.md +188 -0
  2. package/LICENSE +201 -0
  3. package/README.md +129 -0
  4. package/host/APP_AUTHOR_GUIDE.md +646 -0
  5. package/host/README.md +155 -0
  6. package/host/SPEC.md +618 -0
  7. package/host/dist/ReachyHost.d.ts +39 -0
  8. package/host/dist/ReachyHost.d.ts.map +1 -0
  9. package/host/dist/assets/index.d.ts +16 -0
  10. package/host/dist/assets/index.d.ts.map +1 -0
  11. package/host/dist/chunks/index-C3B3FuBC.js +402 -0
  12. package/host/dist/chunks/index-C3B3FuBC.js.map +1 -0
  13. package/host/dist/chunks/mountHost-8f-laxwI.js +48280 -0
  14. package/host/dist/chunks/mountHost-8f-laxwI.js.map +1 -0
  15. package/host/dist/chunks/reachy-mini-sdk-CM-WMoGJ.js +1425 -0
  16. package/host/dist/chunks/reachy-mini-sdk-CM-WMoGJ.js.map +1 -0
  17. package/host/dist/components/ConnectingView.d.ts +13 -0
  18. package/host/dist/components/ConnectingView.d.ts.map +1 -0
  19. package/host/dist/components/EmbedFrame.d.ts +16 -0
  20. package/host/dist/components/EmbedFrame.d.ts.map +1 -0
  21. package/host/dist/components/ErrorView.d.ts +21 -0
  22. package/host/dist/components/ErrorView.d.ts.map +1 -0
  23. package/host/dist/components/LeavingView.d.ts +33 -0
  24. package/host/dist/components/LeavingView.d.ts.map +1 -0
  25. package/host/dist/components/PickerView.d.ts +51 -0
  26. package/host/dist/components/PickerView.d.ts.map +1 -0
  27. package/host/dist/components/ReachyHostShell.d.ts +21 -0
  28. package/host/dist/components/ReachyHostShell.d.ts.map +1 -0
  29. package/host/dist/components/SignInView.d.ts +32 -0
  30. package/host/dist/components/SignInView.d.ts.map +1 -0
  31. package/host/dist/components/StepsProgressIndicator.d.ts +41 -0
  32. package/host/dist/components/StepsProgressIndicator.d.ts.map +1 -0
  33. package/host/dist/components/TopBar.d.ts +52 -0
  34. package/host/dist/components/TopBar.d.ts.map +1 -0
  35. package/host/dist/components/WelcomeBackOverlay.d.ts +28 -0
  36. package/host/dist/components/WelcomeBackOverlay.d.ts.map +1 -0
  37. package/host/dist/embed/index.d.ts +150 -0
  38. package/host/dist/embed/index.d.ts.map +1 -0
  39. package/host/dist/entry/auto.d.ts +12 -0
  40. package/host/dist/entry/auto.d.ts.map +1 -0
  41. package/host/dist/entry/auto.js +7 -0
  42. package/host/dist/entry/auto.js.map +1 -0
  43. package/host/dist/entry/embed.d.ts +12 -0
  44. package/host/dist/entry/embed.d.ts.map +1 -0
  45. package/host/dist/entry/embed.js +7 -0
  46. package/host/dist/entry/embed.js.map +1 -0
  47. package/host/dist/hooks/useHfProfile.d.ts +7 -0
  48. package/host/dist/hooks/useHfProfile.d.ts.map +1 -0
  49. package/host/dist/hooks/useHostBridge.d.ts +37 -0
  50. package/host/dist/hooks/useHostBridge.d.ts.map +1 -0
  51. package/host/dist/hooks/useOAuth.d.ts +16 -0
  52. package/host/dist/hooks/useOAuth.d.ts.map +1 -0
  53. package/host/dist/hooks/useRobots.d.ts +17 -0
  54. package/host/dist/hooks/useRobots.d.ts.map +1 -0
  55. package/host/dist/hooks/useSdk.d.ts +16 -0
  56. package/host/dist/hooks/useSdk.d.ts.map +1 -0
  57. package/host/dist/index.d.ts +25 -0
  58. package/host/dist/index.d.ts.map +1 -0
  59. package/host/dist/index.js +15 -0
  60. package/host/dist/index.js.map +1 -0
  61. package/host/dist/lib/centralListener.d.ts +73 -0
  62. package/host/dist/lib/centralListener.d.ts.map +1 -0
  63. package/host/dist/lib/centralRest.d.ts +35 -0
  64. package/host/dist/lib/centralRest.d.ts.map +1 -0
  65. package/host/dist/lib/protocol.d.ts +230 -0
  66. package/host/dist/lib/protocol.d.ts.map +1 -0
  67. package/host/dist/lib/protocol.js +48 -0
  68. package/host/dist/lib/protocol.js.map +1 -0
  69. package/host/dist/lib/sdk-types.d.ts +46 -0
  70. package/host/dist/lib/sdk-types.d.ts.map +1 -0
  71. package/host/dist/lib/settings.d.ts +69 -0
  72. package/host/dist/lib/settings.d.ts.map +1 -0
  73. package/host/dist/lib/signalingUrl.d.ts +28 -0
  74. package/host/dist/lib/signalingUrl.d.ts.map +1 -0
  75. package/host/dist/lib/theme.d.ts +4 -0
  76. package/host/dist/lib/theme.d.ts.map +1 -0
  77. package/host/dist/lib/themeMode.d.ts +9 -0
  78. package/host/dist/lib/themeMode.d.ts.map +1 -0
  79. package/host/dist/lib/tokens.d.ts +64 -0
  80. package/host/dist/lib/tokens.d.ts.map +1 -0
  81. package/host/dist/mountHost.d.ts +36 -0
  82. package/host/dist/mountHost.d.ts.map +1 -0
  83. package/package.json +109 -0
  84. package/reachy-mini-sdk.d.ts +285 -0
  85. package/reachy-mini-sdk.js +2164 -0
@@ -0,0 +1,1425 @@
1
+ var C = Object.defineProperty, T = (r, e, t) => e in r ? C(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t, b = (r, e, t) => (T(r, typeof e != "symbol" ? e + "" : e, t), t), k = "https://huggingface.co";
2
+ async function y(r, e) {
3
+ var t, s;
4
+ const i = new M(r.url, r.status, (t = r.headers.get("X-Request-Id")) != null ? t : void 0);
5
+ i.message = `Api error with status ${i.statusCode}`;
6
+ const o = [`URL: ${i.url}`, i.requestId ? `Request ID: ${i.requestId}` : void 0].filter(Boolean).join(". ");
7
+ if ((s = r.headers.get("Content-Type")) != null && s.startsWith("application/json")) {
8
+ const n = await r.json();
9
+ i.message = n.error || n.message || i.message, i.data = n;
10
+ } else
11
+ i.data = { message: await r.text() };
12
+ throw i.message += `. ${o}`, i;
13
+ }
14
+ var M = class extends Error {
15
+ constructor(r, e, t, s) {
16
+ super(s), b(this, "statusCode"), b(this, "url"), b(this, "requestId"), b(this, "data"), this.statusCode = e, this.requestId = t, this.url = r;
17
+ }
18
+ };
19
+ new Promise((r) => {
20
+ });
21
+ function A(r) {
22
+ if (globalThis.Buffer)
23
+ return globalThis.Buffer.from(r).toString("base64");
24
+ {
25
+ const e = [];
26
+ return r.forEach((t) => {
27
+ e.push(String.fromCharCode(t));
28
+ }), globalThis.btoa(e.join(""));
29
+ }
30
+ }
31
+ async function R(r) {
32
+ var e, t;
33
+ if (typeof window > "u")
34
+ throw new Error("oauthHandleRedirect is only available in the browser");
35
+ const s = new URLSearchParams(window.location.search), [i, o] = [s.get("error"), s.get("error_description")];
36
+ if (i)
37
+ throw new Error(`${i}: ${o}`);
38
+ const n = s.get("code"), l = localStorage.getItem("huggingface.co:oauth:nonce");
39
+ if (!n)
40
+ throw new Error("Missing oauth code from query parameters in redirected URL");
41
+ if (!l)
42
+ throw new Error("Missing oauth nonce from localStorage");
43
+ const c = localStorage.getItem("huggingface.co:oauth:code_verifier");
44
+ if (!c)
45
+ throw new Error("Missing oauth code_verifier from localStorage");
46
+ const d = s.get("state");
47
+ if (!d)
48
+ throw new Error("Missing oauth state from query parameters in redirected URL");
49
+ let a;
50
+ try {
51
+ a = JSON.parse(d);
52
+ } catch {
53
+ throw new Error("Invalid oauth state in redirected URL, unable to parse JSON: " + d);
54
+ }
55
+ if (a.nonce !== l)
56
+ throw new Error("Invalid oauth state in redirected URL");
57
+ const h = k, u = `${new URL(h).origin}/.well-known/openid-configuration`, m = await fetch(u, {
58
+ headers: {
59
+ Accept: "application/json"
60
+ }
61
+ });
62
+ if (!m.ok)
63
+ throw await y(m);
64
+ const f = await m.json(), v = await fetch(f.token_endpoint, {
65
+ method: "POST",
66
+ headers: {
67
+ "Content-Type": "application/x-www-form-urlencoded"
68
+ },
69
+ body: new URLSearchParams({
70
+ grant_type: "authorization_code",
71
+ code: n,
72
+ redirect_uri: a.redirectUri,
73
+ code_verifier: c
74
+ }).toString()
75
+ });
76
+ if (localStorage.removeItem("huggingface.co:oauth:code_verifier"), localStorage.removeItem("huggingface.co:oauth:nonce"), !v.ok)
77
+ throw await y(v);
78
+ const g = await v.json(), E = new Date(Date.now() + g.expires_in * 1e3), S = await fetch(f.userinfo_endpoint, {
79
+ headers: {
80
+ Authorization: `Bearer ${g.access_token}`
81
+ }
82
+ });
83
+ if (!S.ok)
84
+ throw await y(S);
85
+ const _ = await S.json();
86
+ return {
87
+ accessToken: g.access_token,
88
+ accessTokenExpiresAt: E,
89
+ userInfo: {
90
+ id: _.sub,
91
+ name: _.name,
92
+ fullname: _.preferred_username,
93
+ email: _.email,
94
+ emailVerified: _.email_verified,
95
+ avatarUrl: _.picture,
96
+ websiteUrl: _.website,
97
+ isPro: _.isPro,
98
+ orgs: (t = (e = _.orgs) == null ? void 0 : e.map((p) => ({
99
+ id: p.sub,
100
+ name: p.name,
101
+ fullname: p.name,
102
+ isEnterprise: p.isEnterprise,
103
+ canPay: p.canPay,
104
+ avatarUrl: p.picture,
105
+ roleInOrg: p.roleInOrg
106
+ }))) != null ? t : []
107
+ },
108
+ state: a.state,
109
+ scope: g.scope
110
+ };
111
+ }
112
+ async function j(r) {
113
+ if (typeof window > "u")
114
+ throw new Error("oauthHandleRedirect is only available in the browser");
115
+ const e = new URLSearchParams(window.location.search);
116
+ return e.has("error") ? R() : e.has("code") ? localStorage.getItem("huggingface.co:oauth:nonce") ? R() : (console.warn(
117
+ "Missing oauth nonce from localStorage. This can happen when the user refreshes the page after logging in, without changing the URL."
118
+ ), !1) : !1;
119
+ }
120
+ async function U(r) {
121
+ var e, t;
122
+ if (typeof window > "u")
123
+ throw new Error("oauthLogin is only available in the browser");
124
+ const s = r?.hubUrl || k, i = `${new URL(s).origin}/.well-known/openid-configuration`, o = await fetch(i, {
125
+ headers: {
126
+ Accept: "application/json"
127
+ }
128
+ });
129
+ if (!o.ok)
130
+ throw await y(o);
131
+ const n = await o.json(), l = globalThis.crypto.randomUUID(), c = globalThis.crypto.randomUUID() + globalThis.crypto.randomUUID();
132
+ localStorage.setItem("huggingface.co:oauth:nonce", l), localStorage.setItem("huggingface.co:oauth:code_verifier", c);
133
+ const d = r?.redirectUrl || window.location.href, a = JSON.stringify({
134
+ nonce: l,
135
+ redirectUri: d,
136
+ state: r?.state
137
+ }), h = (t = (e = window?.huggingface) == null ? void 0 : e.variables) != null ? t : null, u = r?.clientId || h?.OAUTH_CLIENT_ID;
138
+ if (!u)
139
+ throw h ? new Error("Missing clientId, please add hf_oauth: true to the README.md's metadata in your static Space") : new Error("Missing clientId");
140
+ const m = A(
141
+ new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(c)))
142
+ ).replace(/[+]/g, "-").replace(/[/]/g, "_").replace(/=/g, "");
143
+ return `${n.authorization_endpoint}?${new URLSearchParams({
144
+ client_id: u,
145
+ scope: r?.scopes || h?.OAUTH_SCOPES || "openid profile",
146
+ response_type: "code",
147
+ redirect_uri: d,
148
+ state: a,
149
+ code_challenge: m,
150
+ code_challenge_method: "S256"
151
+ }).toString()}`;
152
+ }
153
+ function w(r) {
154
+ return r * Math.PI / 180;
155
+ }
156
+ function P(r, e, t) {
157
+ const s = w(r), i = w(e), o = w(t), n = Math.cos(o), l = Math.sin(o), c = Math.cos(i), d = Math.sin(i), a = Math.cos(s), h = Math.sin(s);
158
+ return [
159
+ [n * c, n * d * h - l * a, n * d * a + l * h, 0],
160
+ [l * c, l * d * h + n * a, l * d * a - n * h, 0],
161
+ [-d, c * h, c * a, 0],
162
+ [0, 0, 0, 1]
163
+ ];
164
+ }
165
+ function I(r) {
166
+ const e = Math.round(Number(r) || 0);
167
+ return Math.max(0, Math.min(100, e));
168
+ }
169
+ function L() {
170
+ if (typeof window > "u" || !window.location.hash) return;
171
+ const r = window.location.hash.startsWith("#") ? window.location.hash.slice(1) : window.location.hash;
172
+ let e;
173
+ try {
174
+ e = new URLSearchParams(r);
175
+ } catch {
176
+ return;
177
+ }
178
+ const t = e.get("hf_token");
179
+ if (!t) return;
180
+ const s = e.get("hf_username") || "user", i = e.get("hf_token_expires"), o = i && !Number.isNaN(new Date(i).getTime()) ? i : new Date(Date.now() + 365 * 24 * 60 * 60 * 1e3).toISOString();
181
+ try {
182
+ sessionStorage.setItem("hf_token", t), sessionStorage.setItem("hf_username", s), sessionStorage.setItem("hf_token_expires", o);
183
+ } catch (c) {
184
+ console.warn("[reachy-mini] could not persist pre-seeded HF credentials:", c);
185
+ }
186
+ e.delete("hf_token"), e.delete("hf_username"), e.delete("hf_token_expires");
187
+ const n = e.toString(), l = window.location.pathname + window.location.search + (n ? "#" + n : "");
188
+ try {
189
+ window.history.replaceState(null, "", l);
190
+ } catch {
191
+ }
192
+ }
193
+ function $() {
194
+ if (typeof window > "u") return null;
195
+ if (window.location.hash) {
196
+ const r = window.location.hash.startsWith("#") ? window.location.hash.slice(1) : window.location.hash;
197
+ try {
198
+ const t = new URLSearchParams(r).get("robot_peer_id");
199
+ if (t) return t;
200
+ } catch {
201
+ }
202
+ }
203
+ if (window.location.search)
204
+ try {
205
+ const e = new URLSearchParams(window.location.search).get("robot_peer_id");
206
+ if (e) return e;
207
+ } catch {
208
+ }
209
+ return null;
210
+ }
211
+ function x(r) {
212
+ const e = r.split(`\r
213
+ `);
214
+ let t = !1;
215
+ for (const s of e)
216
+ if (s.startsWith("m=audio") ? t = !0 : s.startsWith("m=") && (t = !1), t && s === "a=sendrecv") return !0;
217
+ return !1;
218
+ }
219
+ class O extends EventTarget {
220
+ /** @param {{ signalingUrl?: string, enableMicrophone?: boolean, clientId?: string, appName?: string, videoJitterBufferTargetMs?: number, autoStartFromUrl?: boolean }} [options] */
221
+ constructor(e = {}) {
222
+ super(), this._signalingUrl = e.signalingUrl || "https://pollen-robotics-reachy-mini-central.hf.space", this._enableMicrophone = e.enableMicrophone !== !1, this._clientId = e.clientId || null, this._appName = e.appName || "unknown", this._videoJitterBufferTargetMs = e.videoJitterBufferTargetMs ?? 0, this._autoStartFromUrl = e.autoStartFromUrl === !0, this._autoStartAttempted = !1, this._state = "disconnected", this._robots = [], this._robotState = {}, this._preselectedRobotId = $(), this._token = null, this._username = null, this._tokenExpires = null, this._peerId = null, this._sseAbortController = null, this._pc = null, this._dc = null, this._sessionId = null, this._selectedRobotId = null, this._micStream = null, this._micMuted = !0, this._audioMuted = !0, this._micSupported = !1, this._latencyMonitorId = null, this._stateRefreshInterval = null, this._versionResolve = null, this._hardwareIdResolve = null, this._volumeResolve = null, this._micVolumeResolve = null, this._logSubscribers = /* @__PURE__ */ new Set(), this._sessionResolve = null, this._sessionReject = null, this._iceConnected = !1, this._dcOpen = !1, this._pendingMotionCompletions = {
223
+ wake_up: [],
224
+ goto_sleep: []
225
+ }, this._videoElement = null;
226
+ }
227
+ // ─── Read-only properties ────────────────────────────────────────────
228
+ /** @returns {"disconnected"|"connected"|"streaming"} */
229
+ get state() {
230
+ return this._state;
231
+ }
232
+ /** @returns {Array<{id: string, meta: {name: string}}>} */
233
+ get robots() {
234
+ return this._robots;
235
+ }
236
+ /**
237
+ * Latest robot state (same shape as the "state" event detail).
238
+ * Mirrors the daemon's wire format — fields appear only once the
239
+ * daemon has sent the corresponding source field. Use the exported
240
+ * math utilities (``matrixToRpy``, ``radToDeg``) for human units.
241
+ * @returns {{
242
+ * head?: number[],
243
+ * antennas?: number[],
244
+ * body_yaw?: number,
245
+ * motor_mode?: "enabled"|"disabled"|"gravity_compensation",
246
+ * is_move_running?: boolean,
247
+ * }}
248
+ */
249
+ get robotState() {
250
+ return this._robotState;
251
+ }
252
+ /** @returns {string|null} HuggingFace username, set after authenticate(). */
253
+ get username() {
254
+ return this._username;
255
+ }
256
+ /** @returns {boolean} True if a valid HF token is available. */
257
+ get isAuthenticated() {
258
+ return !!this._token;
259
+ }
260
+ /** @returns {boolean} True if the robot's SDP offered bidirectional audio. */
261
+ get micSupported() {
262
+ return this._micSupported;
263
+ }
264
+ /** @returns {boolean} */
265
+ get micMuted() {
266
+ return this._micMuted;
267
+ }
268
+ /** @returns {boolean} */
269
+ get audioMuted() {
270
+ return this._audioMuted;
271
+ }
272
+ /**
273
+ * Peer id of the robot the embedding host wants this session to
274
+ * target, captured from the URL at construction time. Apps that
275
+ * want to support iframe-embedding without forcing the user to
276
+ * re-pick a robot read this and pass it straight to
277
+ * `startSession()` once `connect()` resolves:
278
+ *
279
+ * await robot.connect();
280
+ * await robot.startSession(robot.preselectedRobotId ?? pickedId);
281
+ *
282
+ * Returns `null` when the URL carries no `robot_peer_id` (typical
283
+ * standalone Space load). The value is also exposed on the
284
+ * "robotsChanged" payload via the `meta` sidecar for
285
+ * convenience, but the most direct read is right here.
286
+ *
287
+ * @returns {string|null}
288
+ */
289
+ get preselectedRobotId() {
290
+ return this._preselectedRobotId;
291
+ }
292
+ /**
293
+ * Convenience flag for apps that want to branch their UX on
294
+ * "am I embedded in a host shell?". True iff the URL carried a
295
+ * `robot_peer_id` hint at construction time (which only happens
296
+ * when a host iframe — mobile shell, vibe-coder preview, etc. —
297
+ * is the parent). Apps typically use it to skip their robot
298
+ * picker and their sign-in screen, since both are duplicated
299
+ * work the host has already done.
300
+ *
301
+ * @returns {boolean}
302
+ */
303
+ get isEmbedded() {
304
+ return this._preselectedRobotId !== null;
305
+ }
306
+ /**
307
+ * Internal: try to honour the `autoStartFromUrl` constructor
308
+ * option. Called from the signaling-message handler after every
309
+ * `robotsChanged` emit, so a robot that comes online after the
310
+ * SDK is already `connected` still triggers the auto-start.
311
+ * No-op unless `autoStartFromUrl` is set, the URL carries a
312
+ * preselect, the SDK is `connected`, the preselected robot is
313
+ * in the latest list, and we haven't already attempted in this
314
+ * page load. Errors are swallowed to a `console.warn` — the
315
+ * normal `startSession` rejection / `sessionRejected` event
316
+ * still fires for app-level handling.
317
+ *
318
+ * Defers the actual `startSession()` call by one macrotask
319
+ * (`setTimeout(..., 0)`) so it runs OUTSIDE the
320
+ * `_handleSignalingMessage` callstack that just processed the
321
+ * `'list'` message. Reproduced on Android WebView: firing
322
+ * `startSession` synchronously inside the SSE handler races the
323
+ * daemon's setup, leading to a connected-but-no-keyframe state
324
+ * where the receiver eternally NACKs and the iframe shows a
325
+ * black <video>. The macrotask-deferral is the minimum nudge
326
+ * that consistently resolves the race in our reproduction; if
327
+ * it ever proves insufficient on slower hardware, bump to
328
+ * a small explicit delay (e.g. 250 ms).
329
+ */
330
+ _maybeAutoStart() {
331
+ if (!this._autoStartFromUrl || this._autoStartAttempted || !this._preselectedRobotId || this._state !== "connected" || !this._robots.find((s) => s.id === this._preselectedRobotId)) return;
332
+ this._autoStartAttempted = !0;
333
+ const t = this._preselectedRobotId;
334
+ setTimeout(() => {
335
+ this._state === "connected" && this.startSession(t).catch((s) => {
336
+ console.warn("[reachy-mini] autoStartFromUrl: startSession rejected:", s);
337
+ });
338
+ }, 0);
339
+ }
340
+ // ─── Auth ────────────────────────────────────────────────────────────
341
+ /**
342
+ * Check for a valid HuggingFace token.
343
+ *
344
+ * Resolution order:
345
+ * 1. URL fragment hand-off (`#hf_token=…&hf_username=…&hf_token_expires=…`).
346
+ * A host iframe — typically the Reachy Mini mobile app or a
347
+ * vibe-coder preview — can pass credentials through the URL
348
+ * fragment to bypass HF's `X-Frame-Options: SAMEORIGIN` block
349
+ * on `huggingface.co/login`. Seeded into `sessionStorage` and
350
+ * then stripped from the address bar so a page reload does not
351
+ * keep the credentials visible.
352
+ * 2. OAuth redirect callback (standalone Space, first sign-in).
353
+ * 3. `sessionStorage` cache (subsequent loads in any context).
354
+ *
355
+ * @returns {Promise<boolean>} true → token ready, false → call login()
356
+ */
357
+ async authenticate() {
358
+ try {
359
+ L();
360
+ const e = await j();
361
+ if (e)
362
+ return this._username = e.userInfo.preferred_username || e.userInfo.name, this._token = e.accessToken, this._tokenExpires = e.accessTokenExpiresAt, sessionStorage.setItem("hf_token", this._token), sessionStorage.setItem("hf_username", this._username), sessionStorage.setItem("hf_token_expires", this._tokenExpires), !0;
363
+ const t = sessionStorage.getItem("hf_token"), s = sessionStorage.getItem("hf_username"), i = sessionStorage.getItem("hf_token_expires");
364
+ return t && s && i && new Date(i) > /* @__PURE__ */ new Date() ? (this._token = t, this._username = s, this._tokenExpires = i, !0) : !1;
365
+ } catch (e) {
366
+ return console.error("Auth error:", e), !1;
367
+ }
368
+ }
369
+ /** Redirect the browser to the HuggingFace OAuth login page. */
370
+ async login() {
371
+ const e = {};
372
+ this._clientId && (e.clientId = this._clientId), window.location.href = await U(e);
373
+ }
374
+ /** Clear stored HF credentials and disconnect everything. */
375
+ logout() {
376
+ sessionStorage.removeItem("hf_token"), sessionStorage.removeItem("hf_username"), sessionStorage.removeItem("hf_token_expires"), this._username = null, this._tokenExpires = null, this.disconnect();
377
+ }
378
+ // ─── Lifecycle ───────────────────────────────────────────────────────
379
+ /**
380
+ * Open SSE signaling connection. Resolves once the server sends `welcome`.
381
+ * Emits "robotsChanged" as robots come and go.
382
+ * @param {string} [token] — HF access token. Omit to use the one from authenticate().
383
+ * @returns {Promise<void>}
384
+ */
385
+ async connect(e) {
386
+ if (this._state !== "disconnected") throw new Error("Already connected");
387
+ if (e && (this._token = e), !this._token) throw new Error("No token — call authenticate() first or pass a token");
388
+ this._sseAbortController = new AbortController();
389
+ let t;
390
+ try {
391
+ t = await fetch(
392
+ `${this._signalingUrl}/events`,
393
+ {
394
+ signal: this._sseAbortController.signal,
395
+ headers: { Authorization: `Bearer ${this._token}` }
396
+ }
397
+ );
398
+ } catch (s) {
399
+ throw this._sseAbortController = null, s;
400
+ }
401
+ if (!t.ok)
402
+ throw this._sseAbortController = null, new Error(`HTTP ${t.status}`);
403
+ return new Promise((s, i) => {
404
+ let o = !1;
405
+ const n = t.body.getReader(), l = new TextDecoder();
406
+ let c = "";
407
+ (async () => {
408
+ try {
409
+ for (; ; ) {
410
+ const { done: a, value: h } = await n.read();
411
+ if (a) break;
412
+ c += l.decode(h, { stream: !0 });
413
+ const u = c.split(`
414
+ `);
415
+ c = u.pop();
416
+ for (const m of u)
417
+ if (m.startsWith("data:"))
418
+ try {
419
+ const f = JSON.parse(m.slice(5).trim());
420
+ !o && f.type === "welcome" && (o = !0, this._peerId = f.peerId, this._state = "connected", await this._sendToServer({
421
+ type: "setPeerStatus",
422
+ roles: ["listener"],
423
+ meta: { name: this._appName }
424
+ }), this._emit("connected", { peerId: f.peerId }), s()), this._handleSignalingMessage(f);
425
+ } catch {
426
+ }
427
+ }
428
+ } catch (a) {
429
+ if (a.name !== "AbortError" && this._emit("error", { source: "signaling", error: a }), !o) {
430
+ i(a);
431
+ return;
432
+ }
433
+ }
434
+ this._state !== "disconnected" && (this._state = "disconnected", this._emit("disconnected", { reason: "SSE closed" })), o || i(new Error("Connection closed before welcome"));
435
+ })();
436
+ });
437
+ }
438
+ /**
439
+ * One-shot bring-up: auth → SSE connect → robot selection → session →
440
+ * wake up. The all-in-one entry point that captures the common
441
+ * "embed *or* standalone, just get me streaming" flow so each
442
+ * consumer does not have to re-implement it.
443
+ *
444
+ * What it does, in order:
445
+ * 1. **Auth.** If `this._token` is not set, calls `authenticate()`
446
+ * (which honours the iframe URL-fragment hand-off, the OAuth
447
+ * redirect callback, and the `sessionStorage` cache). Throws if
448
+ * none yield a token — the consumer should call `login()` and
449
+ * retry after the redirect. Pass an explicit `token` to skip
450
+ * `authenticate()` entirely.
451
+ * 2. **Connect.** If `state === 'disconnected'`, opens the SSE
452
+ * signaling channel.
453
+ * 3. **Pick a robot.**
454
+ * - **Embed mode** (`this.isEmbedded`): uses
455
+ * `this._preselectedRobotId` from the URL. No picker callback
456
+ * invoked; we briefly wait for that robot to appear in the
457
+ * SSE list, then proceed.
458
+ * - **Standalone**: GETs `/api/robot-status` for the owner's
459
+ * robots with busy state, dedupes by `install_id`, sorts by
460
+ * freshness. If `autoPickIfSingle` and exactly one free, picks
461
+ * it. Else calls the consumer-supplied `pickRobot(robots)`
462
+ * callback. Throws if neither yields an id.
463
+ * 4. **Start session.** Awaits `startSession(robotId)` (ICE + DC).
464
+ * 5. **Wake up.** Awaits `ensureAwake()` so sliders don't silently
465
+ * no-op against a torque-off robot.
466
+ *
467
+ * @param {{
468
+ * token?: string, // skip authenticate(); use this raw HF token
469
+ * pickRobot?: (robots: Array<{
470
+ * id: string,
471
+ * name: string|null,
472
+ * busy: boolean,
473
+ * activeApp: string|null,
474
+ * meta: object,
475
+ * lastSeenAgeSeconds: number|null,
476
+ * }>) => Promise<string|null>, // called only in standalone, multi-robot case
477
+ * autoPickIfSingle?: boolean, // default true — skip the callback when 1 free robot
478
+ * filterBusy?: boolean, // default true — hide busy robots from the picker
479
+ * wakeOnConnect?: boolean, // default true — call ensureAwake() after startSession
480
+ * }} [options]
481
+ * @returns {Promise<{
482
+ * robotId: string,
483
+ * robotName: string|null,
484
+ * isEmbedded: boolean,
485
+ * alreadyStreaming?: boolean,
486
+ * }>}
487
+ */
488
+ async autoConnect(e = {}) {
489
+ const {
490
+ token: t = null,
491
+ pickRobot: s = null,
492
+ autoPickIfSingle: i = !0,
493
+ filterBusy: o = !0,
494
+ wakeOnConnect: n = !0
495
+ } = e;
496
+ if (this._state === "streaming") {
497
+ const c = this._robots?.find((d) => d.id === this._selectedRobotId);
498
+ return {
499
+ robotId: this._selectedRobotId,
500
+ robotName: c?.meta?.name ?? null,
501
+ isEmbedded: this.isEmbedded,
502
+ alreadyStreaming: !0
503
+ };
504
+ }
505
+ const l = this._autoStartFromUrl;
506
+ this._autoStartFromUrl = !1;
507
+ try {
508
+ if (t)
509
+ this._token = t;
510
+ else if (!this._token && !await this.authenticate())
511
+ throw new Error("Not authenticated — call login() or pass a token");
512
+ this._state === "disconnected" && await this.connect();
513
+ let c, d = null;
514
+ if (this.isEmbedded) {
515
+ c = this._preselectedRobotId;
516
+ try {
517
+ await this._waitForRobotInList(c, 5e3);
518
+ } catch {
519
+ }
520
+ d = this._robots?.find((h) => h.id === c)?.meta?.name ?? null;
521
+ } else {
522
+ const a = await this._fetchOwnedRobots({ filterBusy: o });
523
+ if (a.length === 0)
524
+ throw new Error("No reachable robots");
525
+ if (i && a.length === 1 && !a[0].busy)
526
+ c = a[0].id, d = a[0].name;
527
+ else if (s) {
528
+ const h = await s(a);
529
+ if (!h) throw new Error("Robot selection cancelled");
530
+ c = h, d = a.find((u) => u.id === h)?.name ?? null;
531
+ } else
532
+ throw new Error(
533
+ "Multiple robots available — pass a pickRobot callback to autoConnect()"
534
+ );
535
+ }
536
+ if (await this.startSession(c), n && typeof this.ensureAwake == "function")
537
+ try {
538
+ await this.ensureAwake();
539
+ } catch (a) {
540
+ console.warn("[reachy-mini] autoConnect: ensureAwake failed:", a);
541
+ }
542
+ return { robotId: c, robotName: d, isEmbedded: this.isEmbedded };
543
+ } finally {
544
+ this._autoStartFromUrl = l;
545
+ }
546
+ }
547
+ /**
548
+ * Fetch the caller's robots with busy state, deduped + sorted.
549
+ * One-shot snapshot — no live subscription. Falls back to the SSE
550
+ * `_robots` cache if `/api/robot-status` is unavailable (older
551
+ * central deployments don't expose it).
552
+ *
553
+ * Dedup: same physical robot can appear twice transiently after a
554
+ * daemon reinstall (new peerId, same install_id). Last-writer-wins
555
+ * on `install_id`, then `hardware_id`, then `peerId` (= no dedup).
556
+ *
557
+ * @returns {Promise<Array<{
558
+ * id: string,
559
+ * name: string|null,
560
+ * busy: boolean,
561
+ * activeApp: string|null,
562
+ * meta: object,
563
+ * lastSeenAgeSeconds: number|null,
564
+ * }>>}
565
+ */
566
+ async _fetchOwnedRobots({ filterBusy: e = !0 } = {}) {
567
+ try {
568
+ const t = await fetch(`${this._signalingUrl}/api/robot-status`, {
569
+ headers: { Authorization: `Bearer ${this._token}` }
570
+ });
571
+ if (!t.ok) throw new Error(`HTTP ${t.status}`);
572
+ const s = await t.json(), i = /* @__PURE__ */ new Map();
573
+ for (const o of s.robots || []) {
574
+ if (e && o.busy) continue;
575
+ const n = o.meta?.install_id ?? o.meta?.hardware_id ?? o.peerId;
576
+ i.set(n, {
577
+ id: o.peerId,
578
+ name: o.robotName ?? o.meta?.name ?? null,
579
+ busy: !!o.busy,
580
+ activeApp: o.activeApp ?? null,
581
+ meta: o.meta ?? {},
582
+ lastSeenAgeSeconds: o.last_seen_age_seconds ?? null
583
+ });
584
+ }
585
+ return Array.from(i.values()).sort(
586
+ (o, n) => (o.lastSeenAgeSeconds ?? 1 / 0) - (n.lastSeenAgeSeconds ?? 1 / 0)
587
+ );
588
+ } catch (t) {
589
+ return console.warn("[reachy-mini] /api/robot-status unavailable, using SSE list:", t), (this._robots || []).map((s) => ({
590
+ id: s.id,
591
+ name: s.meta?.name ?? null,
592
+ busy: !1,
593
+ // unknown — SSE list does not carry busy state
594
+ activeApp: null,
595
+ meta: s.meta ?? {},
596
+ lastSeenAgeSeconds: null
597
+ }));
598
+ }
599
+ }
600
+ /**
601
+ * Resolve once `robotId` appears in `_robots`, or reject after
602
+ * `timeoutMs`. Used by `autoConnect()`'s embed branch so the preselected
603
+ * robot has a chance to surface from the first SSE `list` push before
604
+ * `startSession()` is fired.
605
+ */
606
+ _waitForRobotInList(e, t) {
607
+ return this._robots?.find((s) => s.id === e) ? Promise.resolve() : new Promise((s, i) => {
608
+ const o = () => {
609
+ this._robots?.find((l) => l.id === e) && (this.removeEventListener("robotsChanged", o), clearTimeout(n), s());
610
+ }, n = setTimeout(() => {
611
+ this.removeEventListener("robotsChanged", o), i(new Error(`Timeout waiting for robot ${e} in list`));
612
+ }, t);
613
+ this.addEventListener("robotsChanged", o);
614
+ });
615
+ }
616
+ /**
617
+ * Start a WebRTC session with the given robot.
618
+ * Acquires the microphone (if enabled), negotiates SDP, and waits for
619
+ * both ICE connection and data channel to be ready before resolving.
620
+ * Emits "videoTrack" when the robot's camera stream arrives.
621
+ * Emits "micSupported" once SDP negotiation reveals whether the robot
622
+ * accepts bidirectional audio.
623
+ * @param {string} robotId — one of the ids from the robots list
624
+ * @returns {Promise<void>}
625
+ */
626
+ async startSession(e) {
627
+ if (this._state !== "connected") throw new Error("Not connected");
628
+ if (this._selectedRobotId = e, this._iceConnected = !1, this._dcOpen = !1, this._micSupported = !1, this._pendingRemoteIce = [], this._enableMicrophone)
629
+ try {
630
+ this._micStream = await navigator.mediaDevices.getUserMedia({ audio: !0 }), this._micStream.getAudioTracks().forEach((t) => {
631
+ t.enabled = !1;
632
+ }), this._micMuted = !0;
633
+ } catch (t) {
634
+ console.warn("Microphone not available:", t);
635
+ try {
636
+ const s = new (window.AudioContext || window.webkitAudioContext)(), i = s.createMediaStreamDestination(), o = s.createOscillator(), n = s.createGain();
637
+ n.gain.value = 0, o.connect(n).connect(i), o.start(), this._micStream = i.stream, this._micStream.getAudioTracks().forEach((l) => {
638
+ l.enabled = !1;
639
+ }), this._micMuted = !0, this._silentMicFallback = { ctx: s, osc: o };
640
+ } catch (s) {
641
+ console.warn("Silent mic fallback failed:", s), this._micStream = null;
642
+ }
643
+ }
644
+ return this._pc = new RTCPeerConnection({
645
+ iceServers: [{ urls: "stun:stun.l.google.com:19302" }]
646
+ }), new Promise((t, s) => {
647
+ this._sessionResolve = t, this._sessionReject = s, this._pc.ontrack = (i) => {
648
+ if (i.track.kind === "video") {
649
+ const o = this._videoJitterBufferTargetMs;
650
+ try {
651
+ i.receiver.jitterBufferTarget = o;
652
+ } catch {
653
+ }
654
+ try {
655
+ i.receiver.playoutDelayHint = o / 1e3;
656
+ } catch {
657
+ }
658
+ this._emit("videoTrack", { track: i.track, stream: i.streams[0] });
659
+ }
660
+ }, this._pc.onicecandidate = async (i) => {
661
+ i.candidate && this._sessionId && await this._sendToServer({
662
+ type: "peer",
663
+ sessionId: this._sessionId,
664
+ ice: {
665
+ candidate: i.candidate.candidate,
666
+ sdpMLineIndex: i.candidate.sdpMLineIndex,
667
+ sdpMid: i.candidate.sdpMid
668
+ }
669
+ });
670
+ }, this._pc.oniceconnectionstatechange = () => {
671
+ const i = this._pc?.iceConnectionState;
672
+ if (i)
673
+ if (i === "connected" || i === "completed")
674
+ this._iceConnected = !0, this._checkSessionReady();
675
+ else if (i === "failed") {
676
+ const o = new Error("ICE connection failed");
677
+ this._sessionReject && (this._sessionReject(o), this._sessionResolve = null, this._sessionReject = null), this._emit("error", { source: "webrtc", error: o });
678
+ } else i === "disconnected" && this._emit("error", { source: "webrtc", error: new Error("ICE disconnected") });
679
+ }, this._pc.ondatachannel = (i) => {
680
+ this._dc = i.channel, this._dc.onopen = () => {
681
+ this._dcOpen = !0, this._checkSessionReady();
682
+ }, this._dc.onmessage = (o) => this._handleRobotMessage(JSON.parse(o.data));
683
+ }, this._sendToServer({ type: "startSession", peerId: e }).then((i) => {
684
+ if (i?.type === "sessionRejected") {
685
+ this._failSessionRejected(i);
686
+ return;
687
+ }
688
+ i?.sessionId && (this._sessionId = i.sessionId);
689
+ });
690
+ });
691
+ }
692
+ /**
693
+ * Internal: handle a sessionRejected response from central.
694
+ * Releases resources allocated by startSession() (RTCPeerConnection,
695
+ * microphone stream) and rejects the pending startSession() promise
696
+ * with an Error carrying `.reason` and `.activeApp`.
697
+ *
698
+ * Called from both the POST-response path (primary) and the SSE
699
+ * handler (defensive, in case the server changes).
700
+ */
701
+ _failSessionRejected(e) {
702
+ const t = new Error(
703
+ e.reason === "robot_busy" ? `Robot is busy: "${e.activeApp || "another app"}" is already connected` : `Session rejected: ${e.reason || "unknown reason"}`
704
+ );
705
+ if (t.reason = e.reason, t.activeApp = e.activeApp, this._pc && (this._pc.close(), this._pc = null), this._micStream && (this._micStream.getTracks().forEach((s) => s.stop()), this._micStream = null), this._iceConnected = !1, this._dcOpen = !1, this._micMuted = !0, this._micSupported = !1, this._emit("sessionRejected", { reason: e.reason, activeApp: e.activeApp }), this._sessionReject) {
706
+ const s = this._sessionReject;
707
+ this._sessionResolve = null, this._sessionReject = null, s(t);
708
+ }
709
+ }
710
+ /**
711
+ * End the WebRTC session. Returns to "connected" state so you can
712
+ * startSession() again with the same or a different robot.
713
+ * @returns {Promise<void>}
714
+ */
715
+ async stopSession() {
716
+ this._versionResolve && (this._versionResolve(null), this._versionResolve = null), this._hardwareIdResolve && (this._hardwareIdResolve(null), this._hardwareIdResolve = null), this._volumeResolve && (this._volumeResolve(null), this._volumeResolve = null), this._micVolumeResolve && (this._micVolumeResolve(null), this._micVolumeResolve = null), this._logSubscribers.clear(), this._rejectPendingMotionCompletions(new Error("Session stopped")), this._sessionReject && (this._sessionReject(new Error("Session stopped")), this._sessionResolve = null, this._sessionReject = null), this._stateRefreshInterval && (clearInterval(this._stateRefreshInterval), this._stateRefreshInterval = null), this._latencyMonitorId && (clearInterval(this._latencyMonitorId), this._latencyMonitorId = null), this._sessionId && await this._sendToServer({ type: "endSession", sessionId: this._sessionId }), this._micStream && (this._micStream.getTracks().forEach((t) => t.stop()), this._micStream = null), this._micMuted = !0, this._micSupported = !1, this._pc && (this._pc.close(), this._pc = null), this._dc && (this._dc.close(), this._dc = null), this._sessionId = null, this._iceConnected = !1, this._dcOpen = !1, this._state === "streaming" && (this._state = "connected", this._emit("sessionStopped", { reason: "user" }));
717
+ }
718
+ /**
719
+ * Full teardown — abort SSE, close WebRTC.
720
+ * Auth state is preserved (call logout() to also clear credentials).
721
+ */
722
+ disconnect() {
723
+ this._sseAbortController && (this._sseAbortController.abort(), this._sseAbortController = null), this._versionResolve && (this._versionResolve(null), this._versionResolve = null), this._hardwareIdResolve && (this._hardwareIdResolve(null), this._hardwareIdResolve = null), this._volumeResolve && (this._volumeResolve(null), this._volumeResolve = null), this._micVolumeResolve && (this._micVolumeResolve(null), this._micVolumeResolve = null), this._logSubscribers.clear(), this._rejectPendingMotionCompletions(new Error("Disconnected")), this._sessionReject && (this._sessionReject(new Error("Disconnected")), this._sessionResolve = null, this._sessionReject = null), this._stateRefreshInterval && (clearInterval(this._stateRefreshInterval), this._stateRefreshInterval = null), this._latencyMonitorId && (clearInterval(this._latencyMonitorId), this._latencyMonitorId = null), this._sessionId && this._token && this._sendToServer({ type: "endSession", sessionId: this._sessionId }), this._micStream && (this._micStream.getTracks().forEach((e) => e.stop()), this._micStream = null), this._pc && (this._pc.close(), this._pc = null), this._dc && (this._dc.close(), this._dc = null), this._sessionId = null, this._micMuted = !0, this._micSupported = !1, this._iceConnected = !1, this._dcOpen = !1, this._peerId = null, this._robots = [], this._state = "disconnected", this._emit("disconnected", { reason: "user" });
724
+ }
725
+ // ─── Commands ────────────────────────────────────────────────────────
726
+ // All return false if the data channel is not open, true if sent.
727
+ /**
728
+ * Send a target pose to the robot. Wire-shape, raw units only —
729
+ * single source of truth for motion commands. Every field is
730
+ * optional; omitted fields leave the daemon's previous target
731
+ * unchanged, so partial updates compose naturally.
732
+ *
733
+ * For human units (degrees), use the ``setHeadRpyDeg`` /
734
+ * ``setAntennasDeg`` / ``setBodyYawDeg`` thin wrappers below.
735
+ *
736
+ * @param {object} [target]
737
+ * @param {number[]} [target.head] 16-element flat row-major 4×4
738
+ * matrix (full SE(3); preserves translation, no XYZ loss).
739
+ * @param {number[]} [target.antennas] ``[rightRad, leftRad]``.
740
+ * @param {number} [target.body_yaw] Body yaw in radians.
741
+ * @returns {boolean} false if the data channel is not open.
742
+ * @throws {TypeError} if any provided field has the wrong shape or
743
+ * contains a non-finite value (NaN, Infinity). Validation runs at
744
+ * the JS boundary so caller mistakes surface with a stack trace
745
+ * pointing to the call site, not as a confusing daemon-side error.
746
+ */
747
+ setTarget({ head: e, antennas: t, body_yaw: s } = {}) {
748
+ const i = { type: "set_full_target" };
749
+ if (e !== void 0) {
750
+ if (!Array.isArray(e) || e.length !== 16 || !e.every((o) => Number.isFinite(o)))
751
+ throw new TypeError(
752
+ `setTarget: head must be a 16-element flat row-major 4×4 matrix of finite numbers; got ${Array.isArray(e) ? `Array(${e.length})` : typeof e}`
753
+ );
754
+ i.head = e;
755
+ }
756
+ if (t !== void 0) {
757
+ if (!Array.isArray(t) || t.length !== 2 || !t.every((o) => Number.isFinite(o)))
758
+ throw new TypeError(
759
+ `setTarget: antennas must be [rightRad, leftRad] (2 finite numbers); got ${Array.isArray(t) ? `Array(${t.length})` : typeof t}`
760
+ );
761
+ i.antennas = t;
762
+ }
763
+ if (s !== void 0) {
764
+ if (!Number.isFinite(s))
765
+ throw new TypeError(
766
+ `setTarget: body_yaw must be a finite number (radians); got ${s}`
767
+ );
768
+ i.body_yaw = s;
769
+ }
770
+ return this._sendCommand(i);
771
+ }
772
+ /**
773
+ * Smooth daemon-side interpolation to a target pose over
774
+ * ``duration`` seconds. Mirrors ``setTarget``'s wire shape (head
775
+ * is a 16-element flat row-major 4×4, antennas are
776
+ * ``[rightRad, leftRad]``, body_yaw is radians) and adds a
777
+ * required ``duration`` field. The daemon dispatches the command
778
+ * to its lerp planner instead of jumping to the target.
779
+ *
780
+ * Use this for one-shot smooth approaches to an arbitrary pose
781
+ * (e.g. soft-return-to-base after recording, or pre-positioning
782
+ * before a streamed playback). For continuous streamed motion,
783
+ * use ``setTarget`` and lerp client-side.
784
+ *
785
+ * @param {{head?: number[], antennas?: number[], body_yaw?: number, duration: number}} args
786
+ * @returns {boolean} false if the data channel is not open.
787
+ * @throws {TypeError} if any provided field has the wrong shape
788
+ * or contains a non-finite value (NaN, Infinity), or if
789
+ * ``duration`` is missing or non-positive.
790
+ */
791
+ gotoTarget({ head: e, antennas: t, body_yaw: s, duration: i } = {}) {
792
+ const o = { type: "goto_target" };
793
+ if (e !== void 0) {
794
+ if (!Array.isArray(e) || e.length !== 16 || !e.every((n) => Number.isFinite(n)))
795
+ throw new TypeError(
796
+ `gotoTarget: head must be a 16-element flat row-major 4×4 matrix of finite numbers; got ${Array.isArray(e) ? `Array(${e.length})` : typeof e}`
797
+ );
798
+ o.head = e;
799
+ }
800
+ if (t !== void 0) {
801
+ if (!Array.isArray(t) || t.length !== 2 || !t.every((n) => Number.isFinite(n)))
802
+ throw new TypeError(
803
+ `gotoTarget: antennas must be [rightRad, leftRad] (2 finite numbers); got ${Array.isArray(t) ? `Array(${t.length})` : typeof t}`
804
+ );
805
+ o.antennas = t;
806
+ }
807
+ if (s !== void 0) {
808
+ if (!Number.isFinite(s))
809
+ throw new TypeError(
810
+ `gotoTarget: body_yaw must be a finite number (radians); got ${s}`
811
+ );
812
+ o.body_yaw = s;
813
+ }
814
+ if (!Number.isFinite(i) || i <= 0)
815
+ throw new TypeError(
816
+ `gotoTarget: duration must be a positive finite number (seconds); got ${i}`
817
+ );
818
+ return o.duration = i, this._sendCommand(o);
819
+ }
820
+ /**
821
+ * Set head orientation from roll/pitch/yaw in degrees.
822
+ * Convenience wrapper over ``setTarget``.
823
+ * @param {number} rollDeg @param {number} pitchDeg @param {number} yawDeg
824
+ * @returns {boolean}
825
+ */
826
+ setHeadRpyDeg(e, t, s) {
827
+ return this.setTarget({ head: P(e, t, s).flat() });
828
+ }
829
+ /**
830
+ * Set antenna positions from degrees.
831
+ * Convenience wrapper over ``setTarget``.
832
+ * @param {number} rightDeg @param {number} leftDeg
833
+ * @returns {boolean}
834
+ */
835
+ setAntennasDeg(e, t) {
836
+ return this.setTarget({ antennas: [w(e), w(t)] });
837
+ }
838
+ /**
839
+ * Set body yaw from degrees.
840
+ * Convenience wrapper over ``setTarget``.
841
+ * @param {number} yawDeg
842
+ * @returns {boolean}
843
+ */
844
+ setBodyYawDeg(e) {
845
+ return this.setTarget({ body_yaw: w(e) });
846
+ }
847
+ /**
848
+ * Play a sound file on the robot.
849
+ * @param {string} file — filename available on the robot (e.g. "wake_up.wav")
850
+ * @returns {boolean}
851
+ */
852
+ playSound(e) {
853
+ return this._sendCommand({ type: "play_sound", file: e });
854
+ }
855
+ /**
856
+ * Set the motor control mode.
857
+ *
858
+ * @param {"enabled"|"disabled"|"gravity_compensation"} mode
859
+ * - "enabled" torque on, position-controlled.
860
+ * - "disabled" torque off; the robot is backdrivable
861
+ * and will not hold any pose.
862
+ * - "gravity_compensation" torque on in current-control mode;
863
+ * motors actively cancel gravity so the
864
+ * robot is easy to move by hand.
865
+ * @returns {boolean} false if the data channel is not open.
866
+ */
867
+ setMotorMode(e) {
868
+ return this._sendCommand({ type: "set_motor_mode", mode: e });
869
+ }
870
+ /**
871
+ * Toggle torque on/off, optionally per-motor.
872
+ *
873
+ * @param {boolean} on
874
+ * @param {string[]} [ids] motor names (e.g. ["left_antenna"]). When
875
+ * omitted, applies globally — equivalent to setMotorMode("enabled"
876
+ * | "disabled").
877
+ * @returns {boolean} false if the data channel is not open.
878
+ */
879
+ setMotorTorque(e, t = null) {
880
+ return this._sendCommand({ type: "set_torque", on: e, ids: t });
881
+ }
882
+ /**
883
+ * Play the wake-up animation (full head/antennas trajectory on the
884
+ * robot, ~1-3 s depending on the starting head pose) and resolve
885
+ * when the daemon reports the trajectory player has actually
886
+ * finished.
887
+ *
888
+ * This helper sends a ``set_motor_mode: "enabled"`` command *before*
889
+ * the ``wake_up`` command so the animation actually moves the motors.
890
+ * The robot's ``wake_up`` handler does not touch motor mode itself;
891
+ * if torque is off when the trajectory runs, the commanded positions
892
+ * are silently ignored and the robot stays limp. Both commands
893
+ * travel over the same data channel so ordering at the backend is
894
+ * preserved.
895
+ *
896
+ * The returned promise resolves on the daemon's
897
+ * ``{command: "wake_up", completed: true}`` response (sent after
898
+ * the trajectory player is fully done, not just when the command
899
+ * is enqueued). Lets a UI overlay (e.g. the host's "Wake-up" step)
900
+ * stay up for exactly the right duration, and lets callers chain
901
+ * setup that depends on the head being in the awake pose without
902
+ * racing the trajectory.
903
+ *
904
+ * Semantics match the REST endpoint ``POST /api/move/play/wake_up``
905
+ * plus the LAN convention of enabling motors before playing motion
906
+ * trajectories.
907
+ *
908
+ * @param {object} [options]
909
+ * @param {number} [options.timeoutMs=8000] hard upper bound; the
910
+ * promise rejects with a TimeoutError-shaped Error if the daemon
911
+ * stops responding (e.g. data channel went down mid-animation
912
+ * without firing close events).
913
+ * @returns {Promise<void>}
914
+ */
915
+ wakeUp({ timeoutMs: e = 8e3 } = {}) {
916
+ return this._sendCommand({ type: "set_motor_mode", mode: "enabled" }), this._sendCommandAwaitCompletion("wake_up", e);
917
+ }
918
+ /**
919
+ * Play the goto-sleep animation and resolve when the daemon reports
920
+ * the trajectory player has finished. See ``wakeUp`` for the
921
+ * completion-signal rationale.
922
+ *
923
+ * Does NOT touch motor mode: the daemon's ``goto_sleep`` handler
924
+ * manages the transition out of torque on its own (motors must stay
925
+ * powered during the trajectory to move into the sleep pose, then
926
+ * are typically disabled by the daemon once the pose is reached).
927
+ *
928
+ * The awaitable form lets callers chain ``setMotorMode('disabled')``
929
+ * AFTER the trajectory lands instead of racing it, which previously
930
+ * caused the head to drop mid-animation when consumers tore down
931
+ * too eagerly.
932
+ *
933
+ * Semantics match ``POST /api/move/play/goto_sleep`` and the
934
+ * ``"goto_sleep"`` WebRTC command.
935
+ *
936
+ * @param {object} [options]
937
+ * @param {number} [options.timeoutMs=8000]
938
+ * @returns {Promise<void>}
939
+ */
940
+ gotoSleep({ timeoutMs: e = 8e3 } = {}) {
941
+ return this._sendCommandAwaitCompletion("goto_sleep", e);
942
+ }
943
+ /**
944
+ * Internal: send a motion command and resolve when the daemon's
945
+ * matching ``{command, completed: true}`` response lands.
946
+ *
947
+ * Pushes one entry onto ``_pendingMotionCompletions[command]``; the
948
+ * data-channel reader (``_handleRobotMessage``) shifts the oldest
949
+ * entry off the queue when a response arrives, which preserves the
950
+ * FIFO matching that the daemon's serialised dispatcher relies on.
951
+ *
952
+ * Rejects immediately if the data channel is not open; the underlying
953
+ * ``_sendCommand`` returns false in that case and we never enqueue an
954
+ * awaiter that the daemon could never reach.
955
+ *
956
+ * @param {"wake_up"|"goto_sleep"} command
957
+ * @param {number} timeoutMs
958
+ * @returns {Promise<void>}
959
+ */
960
+ _sendCommandAwaitCompletion(e, t) {
961
+ return this._sendCommand({ type: e }) ? new Promise((s, i) => {
962
+ const o = {
963
+ resolve: s,
964
+ reject: i,
965
+ timer: setTimeout(() => {
966
+ const n = this._pendingMotionCompletions[e], l = n.indexOf(o);
967
+ l !== -1 && n.splice(l, 1), i(new Error(`${e} timed out after ${t}ms`));
968
+ }, t)
969
+ };
970
+ this._pendingMotionCompletions[e].push(o);
971
+ }) : Promise.reject(new Error(`${e}: data channel not open`));
972
+ }
973
+ /**
974
+ * Internal: drain every pending motion-completion resolver with the
975
+ * given error. Called by ``stopSession()`` and ``disconnect()`` so a
976
+ * teardown that interrupts an in-flight ``gotoSleep`` does not leave
977
+ * the caller awaiting forever.
978
+ */
979
+ _rejectPendingMotionCompletions(e) {
980
+ for (const t of Object.keys(this._pendingMotionCompletions)) {
981
+ const s = this._pendingMotionCompletions[t];
982
+ for (; s.length; ) {
983
+ const i = s.shift();
984
+ clearTimeout(i.timer), i.reject(e);
985
+ }
986
+ }
987
+ }
988
+ /**
989
+ * Whether the robot's motors are currently powered (the "awake" state).
990
+ *
991
+ * Reads ``motor_mode`` from the last state event. Both ``"enabled"``
992
+ * and ``"gravity_compensation"`` count as awake: in gravity-comp the
993
+ * motors are actively holding the arm against gravity, so the robot
994
+ * is *not* limp and playing wake_up on top would fight the user.
995
+ * Only ``"disabled"`` (true sleep) is considered not-awake.
996
+ *
997
+ * Returns ``false`` before the first state event arrives (typical
998
+ * right after ``startSession()``). Use ``ensureAwake()`` if you want
999
+ * to wait for the first state before deciding.
1000
+ *
1001
+ * @returns {boolean}
1002
+ */
1003
+ isAwake() {
1004
+ const e = this._robotState?.motor_mode;
1005
+ return e === "enabled" || e === "gravity_compensation";
1006
+ }
1007
+ /**
1008
+ * Wake the robot up if it is currently asleep, otherwise no-op.
1009
+ *
1010
+ * Intended as the first line of any app after ``startSession()``
1011
+ * resolves — robots are often left in the sleep pose (torque off,
1012
+ * head resting on the base) and commanded positions are silently
1013
+ * ignored in that state.
1014
+ *
1015
+ * If no state event has arrived yet, waits up to ``timeoutMs`` for
1016
+ * one before deciding. If still no state, falls back to sending
1017
+ * ``wakeUp()`` (safe: the daemon's wake_up handler is idempotent
1018
+ * at the motion level — it moves to the awake pose from wherever
1019
+ * the head currently is).
1020
+ *
1021
+ * @param {number} [timeoutMs=1000] how long to wait for the first
1022
+ * state event before falling through to wakeUp().
1023
+ * @returns {Promise<boolean>} true if the robot is awake afterwards.
1024
+ */
1025
+ async ensureAwake(e = 1e3) {
1026
+ return this._robotState?.motor_mode === void 0 && await new Promise((t) => {
1027
+ const s = () => {
1028
+ this.removeEventListener("state", s), clearTimeout(i), t();
1029
+ }, i = setTimeout(s, e);
1030
+ this.addEventListener("state", s), this.requestState();
1031
+ }), this.isAwake() || this.wakeUp().catch(() => {
1032
+ }), !0;
1033
+ }
1034
+ /**
1035
+ * Request the daemon version.
1036
+ * Resolves with the version string (or null if unavailable).
1037
+ * @returns {Promise<string|null>}
1038
+ */
1039
+ getVersion() {
1040
+ return new Promise((e, t) => {
1041
+ if (!this._dc || this._dc.readyState !== "open") {
1042
+ t(new Error("Data channel not open"));
1043
+ return;
1044
+ }
1045
+ this._versionResolve && this._versionResolve(null), this._versionResolve = e, this._sendCommand({ type: "get_version" });
1046
+ });
1047
+ }
1048
+ /**
1049
+ * Request the robot's unique hardware ID — the Pollen audio device's
1050
+ * USB serial. Same value across Lite and Wireless variants, stable
1051
+ * across reboots and OS reinstalls. Useful for fleet management,
1052
+ * per-robot calibration cache keys, or identifying which physical
1053
+ * robot a session is bound to.
1054
+ * Resolves with the hardware ID string (or null if no robot is
1055
+ * attached, e.g. the daemon is running on a developer machine).
1056
+ * @returns {Promise<string|null>}
1057
+ */
1058
+ getHardwareId() {
1059
+ return new Promise((e, t) => {
1060
+ if (!this._dc || this._dc.readyState !== "open") {
1061
+ t(new Error("Data channel not open"));
1062
+ return;
1063
+ }
1064
+ this._hardwareIdResolve && this._hardwareIdResolve(null), this._hardwareIdResolve = e, this._sendCommand({ type: "get_hardware_id" });
1065
+ });
1066
+ }
1067
+ /**
1068
+ * Query the current speaker volume (0-100).
1069
+ * Resolves with null if volume control is unavailable (platform unsupported
1070
+ * or audio stack down).
1071
+ * @returns {Promise<number|null>}
1072
+ */
1073
+ getVolume() {
1074
+ return this._volumeRoundtrip({ type: "get_volume" }, "_volumeResolve");
1075
+ }
1076
+ /**
1077
+ * Set the speaker volume (0-100). Persists for the next connection
1078
+ * (same semantics as the REST /api/volume/set endpoint).
1079
+ * Resolves with the applied volume, or null on failure.
1080
+ * @param {number} volume 0-100
1081
+ * @returns {Promise<number|null>}
1082
+ */
1083
+ setVolume(e) {
1084
+ return this._volumeRoundtrip(
1085
+ { type: "set_volume", volume: I(e) },
1086
+ "_volumeResolve"
1087
+ );
1088
+ }
1089
+ /**
1090
+ * Query the current microphone input volume (0-100).
1091
+ * @returns {Promise<number|null>}
1092
+ */
1093
+ getMicrophoneVolume() {
1094
+ return this._volumeRoundtrip(
1095
+ { type: "get_microphone_volume" },
1096
+ "_micVolumeResolve"
1097
+ );
1098
+ }
1099
+ /**
1100
+ * Set the microphone input volume (0-100). Persists across sessions.
1101
+ * @param {number} volume 0-100
1102
+ * @returns {Promise<number|null>}
1103
+ */
1104
+ setMicrophoneVolume(e) {
1105
+ return this._volumeRoundtrip(
1106
+ { type: "set_microphone_volume", volume: I(e) },
1107
+ "_micVolumeResolve"
1108
+ );
1109
+ }
1110
+ /**
1111
+ * Internal: send a volume command and await the single-slot response.
1112
+ * The slot name selects which resolver (speaker vs mic) owns the
1113
+ * pending request so the two can be in-flight concurrently without
1114
+ * collision.
1115
+ */
1116
+ _volumeRoundtrip(e, t) {
1117
+ return new Promise((s, i) => {
1118
+ if (!this._dc || this._dc.readyState !== "open") {
1119
+ i(new Error("Data channel not open"));
1120
+ return;
1121
+ }
1122
+ this[t] && this[t](null), this[t] = s, this._sendCommand(e);
1123
+ });
1124
+ }
1125
+ /**
1126
+ * Send an arbitrary JSON command over the data channel.
1127
+ * @param {object} data @returns {boolean}
1128
+ */
1129
+ sendRaw(e) {
1130
+ return this._sendCommand(e);
1131
+ }
1132
+ /**
1133
+ * Subscribe to the daemon's `journalctl -u reachy-mini-daemon`
1134
+ * stream over the WebRTC data channel.
1135
+ *
1136
+ * One daemon-side subprocess is shared across all local subscribers:
1137
+ * the first call sends `subscribe_logs`, removing the last subscriber
1138
+ * sends `unsubscribe_logs`. Calling the returned `unsubscribe()`
1139
+ * twice is a no-op.
1140
+ *
1141
+ * @param {{
1142
+ * onLine: (entry: { timestamp: string, line: string }) => void,
1143
+ * onError?: (error: string) => void,
1144
+ * }} options
1145
+ * @returns {() => void} unsubscribe
1146
+ */
1147
+ subscribeLogs({ onLine: e, onError: t } = {}) {
1148
+ if (typeof e != "function")
1149
+ throw new TypeError("subscribeLogs: onLine callback is required");
1150
+ const s = { onLine: e, onError: t }, i = this._logSubscribers.size === 0;
1151
+ this._logSubscribers.add(s), i && this._sendCommand({ type: "subscribe_logs" });
1152
+ let o = !1;
1153
+ return () => {
1154
+ o || (o = !0, this._logSubscribers.delete(s), this._logSubscribers.size === 0 && this._sendCommand({ type: "unsubscribe_logs" }));
1155
+ };
1156
+ }
1157
+ /**
1158
+ * Request a state snapshot. The response arrives as a "state" event.
1159
+ * Called automatically every 500 ms while streaming.
1160
+ *
1161
+ * Safe to call at a higher rate if you need faster telemetry: e.g.
1162
+ * ``setInterval(() => robot.requestState(), 20)`` for ~50 Hz, or drive
1163
+ * it from a ``requestAnimationFrame`` loop for display-rate updates.
1164
+ * On LAN the daemon can sustain ~90-100 Hz round-trips over the
1165
+ * datachannel; over the internet expect the WebRTC path's RTT to
1166
+ * dominate. The built-in 500 ms poll keeps running in parallel — it
1167
+ * is harmless, as state responses are idempotent.
1168
+ *
1169
+ * @returns {boolean}
1170
+ */
1171
+ requestState() {
1172
+ return this._sendCommand({ type: "get_state" });
1173
+ }
1174
+ // ─── Audio ───────────────────────────────────────────────────────────
1175
+ /**
1176
+ * Mute/unmute the robot's audio playback (speaker) locally.
1177
+ * Audio is muted by default — browsers require a user gesture to unmute.
1178
+ * @param {boolean} muted
1179
+ */
1180
+ setAudioMuted(e) {
1181
+ this._audioMuted = e, this._videoElement && (this._videoElement.muted = e);
1182
+ }
1183
+ /**
1184
+ * Mute/unmute your microphone. Only works if micSupported is true.
1185
+ * Mic is muted by default even after acquisition.
1186
+ * @param {boolean} muted
1187
+ */
1188
+ setMicMuted(e) {
1189
+ this._micMuted = e, this._micStream && this._micStream.getAudioTracks().forEach((t) => {
1190
+ t.enabled = !e;
1191
+ });
1192
+ }
1193
+ // ─── Video helper ────────────────────────────────────────────────────
1194
+ /**
1195
+ * Bind a `<video>` element to this robot's stream.
1196
+ * Call before startSession(). Sets srcObject when the video track arrives,
1197
+ * applies audio mute state, and runs a latency monitor that snaps to the
1198
+ * live edge if the buffer grows > 0.5 s.
1199
+ *
1200
+ * @param {HTMLVideoElement} videoElement
1201
+ * @returns {() => void} cleanup function — call to detach video and stop monitoring
1202
+ */
1203
+ attachVideo(e) {
1204
+ this._videoElement = e, e.muted = this._audioMuted;
1205
+ const t = (i) => {
1206
+ e.srcObject = i.detail.stream, e.playsInline = !0, "requestVideoFrameCallback" in e && this._startLatencyMonitor(e);
1207
+ }, s = () => {
1208
+ e.srcObject = null;
1209
+ };
1210
+ return this.addEventListener("videoTrack", t), this.addEventListener("sessionStopped", s), () => {
1211
+ this.removeEventListener("videoTrack", t), this.removeEventListener("sessionStopped", s), this._latencyMonitorId && (clearInterval(this._latencyMonitorId), this._latencyMonitorId = null), e.srcObject = null, this._videoElement = null;
1212
+ };
1213
+ }
1214
+ // ─── Private ─────────────────────────────────────────────────────────
1215
+ _emit(e, t) {
1216
+ this.dispatchEvent(new CustomEvent(e, { detail: t }));
1217
+ }
1218
+ async _sendToServer(e) {
1219
+ if (!this._token) throw new Error("No token — authenticate() first");
1220
+ try {
1221
+ const t = await fetch(`${this._signalingUrl}/send`, {
1222
+ method: "POST",
1223
+ headers: {
1224
+ "Content-Type": "application/json",
1225
+ Authorization: `Bearer ${this._token}`
1226
+ },
1227
+ body: JSON.stringify(e)
1228
+ });
1229
+ if (!t.ok) {
1230
+ let s = "";
1231
+ try {
1232
+ s = await t.text();
1233
+ } catch {
1234
+ }
1235
+ return console.warn(
1236
+ `[reachy-mini] /send rejected (${t.status}) for type=${e?.type}; body=${s || "<empty>"}`
1237
+ ), null;
1238
+ }
1239
+ return await t.json();
1240
+ } catch (t) {
1241
+ return console.error("Send error:", t), null;
1242
+ }
1243
+ }
1244
+ _sendCommand(e) {
1245
+ return !this._dc || this._dc.readyState !== "open" ? !1 : (this._dc.send(JSON.stringify(e)), !0);
1246
+ }
1247
+ /** Resolves the startSession() promise once both ICE and datachannel are ready. */
1248
+ _checkSessionReady() {
1249
+ this._iceConnected && this._dcOpen && this._sessionResolve && (this._state = "streaming", this.requestState(), this._stateRefreshInterval = setInterval(() => this.requestState(), 500), this._emit("streaming", { sessionId: this._sessionId, robotId: this._selectedRobotId }), this._sessionResolve(), this._sessionResolve = null, this._sessionReject = null);
1250
+ }
1251
+ async _handleSignalingMessage(e) {
1252
+ switch (e.type) {
1253
+ case "welcome":
1254
+ break;
1255
+ // handled in connect()
1256
+ case "list":
1257
+ this._robots = e.producers || [], this._emit("robotsChanged", { robots: this._robots }), this._maybeAutoStart();
1258
+ break;
1259
+ case "peerStatusChanged": {
1260
+ const t = await this._sendToServer({ type: "list" });
1261
+ t?.producers && (this._robots = t.producers, this._emit("robotsChanged", { robots: this._robots }), this._maybeAutoStart());
1262
+ break;
1263
+ }
1264
+ case "sessionStarted":
1265
+ this._sessionId = e.sessionId;
1266
+ break;
1267
+ case "sessionRejected":
1268
+ this._failSessionRejected(e);
1269
+ break;
1270
+ case "endSession":
1271
+ this._handleEndSession(e);
1272
+ break;
1273
+ case "peer":
1274
+ this._handlePeerMessage(e);
1275
+ break;
1276
+ }
1277
+ }
1278
+ /**
1279
+ * Internal: handle an endSession pushed from central.
1280
+ *
1281
+ * Two user-visible scenarios converge here:
1282
+ *
1283
+ * 1. Pending startSession — central accepted our request but the
1284
+ * robot-side relay then refused (e.g. a local Python app holds
1285
+ * the daemon's robot lock). Without this handler, the client's
1286
+ * startSession() promise would hang forever because ICE/datachannel
1287
+ * never come up.
1288
+ * 2. Streaming was evicted — a local Python app started on the robot
1289
+ * while we were connected, so the relay tore down our session.
1290
+ *
1291
+ * The ``reason`` is forwarded verbatim from the relay through central:
1292
+ * - "robot_busy_local_app": daemon lock held by a local Python app
1293
+ * (refused before any media negotiation).
1294
+ * - "local_app_started": a local Python app started mid-session and
1295
+ * evicted us.
1296
+ * - "robot_busy_local": relay's safety-net for stale/concurrent
1297
+ * sessions (should be rare).
1298
+ */
1299
+ _handleEndSession(e) {
1300
+ const t = e.reason, s = t === "robot_busy_local_app" ? "Robot is busy: a local Python app is running" : t === "local_app_started" ? "Disconnected: a local Python app started on the robot" : t === "robot_busy_local" ? "Robot is busy: another session is already active" : null;
1301
+ if (this._sessionReject) {
1302
+ const i = new Error(
1303
+ s || `Session ended before it could start: ${t || "unknown reason"}`
1304
+ );
1305
+ i.reason = t, this._emit("sessionRejected", { reason: t, activeApp: null }), this._pc && (this._pc.close(), this._pc = null), this._micStream && (this._micStream.getTracks().forEach((n) => n.stop()), this._micStream = null), this._iceConnected = !1, this._dcOpen = !1, this._micMuted = !0, this._micSupported = !1;
1306
+ const o = this._sessionReject;
1307
+ this._sessionResolve = null, this._sessionReject = null, o(i);
1308
+ return;
1309
+ }
1310
+ this._state === "streaming" && (this._emit("sessionStopped", {
1311
+ reason: t || "remote_end",
1312
+ message: s
1313
+ }), this.stopSession().catch(() => {
1314
+ }));
1315
+ }
1316
+ async _handlePeerMessage(e) {
1317
+ if (this._pc)
1318
+ try {
1319
+ if (e.sdp) {
1320
+ const t = e.sdp;
1321
+ if (t.type === "offer") {
1322
+ const i = x(t.sdp);
1323
+ if (this._micSupported = i, this._emit("micSupported", { supported: i }), i && this._micStream)
1324
+ for (const n of this._micStream.getAudioTracks())
1325
+ this._pc.addTrack(n, this._micStream);
1326
+ await this._pc.setRemoteDescription(new RTCSessionDescription(t));
1327
+ const o = await this._pc.createAnswer();
1328
+ await this._pc.setLocalDescription(o), await this._sendToServer({
1329
+ type: "peer",
1330
+ sessionId: this._sessionId,
1331
+ sdp: { type: "answer", sdp: o.sdp }
1332
+ });
1333
+ } else
1334
+ await this._pc.setRemoteDescription(new RTCSessionDescription(t));
1335
+ const s = this._pendingRemoteIce;
1336
+ if (s && s.length) {
1337
+ this._pendingRemoteIce = [];
1338
+ for (const i of s)
1339
+ try {
1340
+ await this._pc.addIceCandidate(new RTCIceCandidate(i));
1341
+ } catch (o) {
1342
+ console.warn("[reachy-mini] buffered ICE candidate rejected:", o);
1343
+ }
1344
+ }
1345
+ }
1346
+ if (e.ice) {
1347
+ if (!e.ice.candidate) return;
1348
+ this._pc.remoteDescription ? await this._pc.addIceCandidate(new RTCIceCandidate(e.ice)) : (this._pendingRemoteIce || (this._pendingRemoteIce = []), this._pendingRemoteIce.push(e.ice));
1349
+ }
1350
+ } catch (t) {
1351
+ console.error("WebRTC error:", t), this._emit("error", { source: "webrtc", error: t });
1352
+ }
1353
+ }
1354
+ /** Parse robot messages and dispatch. */
1355
+ _handleRobotMessage(e) {
1356
+ if ("version" in e && this._versionResolve) {
1357
+ this._versionResolve(e.version), this._versionResolve = null;
1358
+ return;
1359
+ }
1360
+ if ("hardware_id" in e && this._hardwareIdResolve) {
1361
+ this._hardwareIdResolve(e.hardware_id), this._hardwareIdResolve = null;
1362
+ return;
1363
+ }
1364
+ if (e.command === "get_volume" || e.command === "set_volume") {
1365
+ this._volumeResolve && (this._volumeResolve(e.status === "error" ? null : e.volume), this._volumeResolve = null);
1366
+ return;
1367
+ }
1368
+ if (e.command === "get_microphone_volume" || e.command === "set_microphone_volume") {
1369
+ this._micVolumeResolve && (this._micVolumeResolve(e.status === "error" ? null : e.volume), this._micVolumeResolve = null);
1370
+ return;
1371
+ }
1372
+ if ((e.command === "wake_up" || e.command === "goto_sleep") && this._pendingMotionCompletions && this._pendingMotionCompletions[e.command]) {
1373
+ const t = this._pendingMotionCompletions[e.command];
1374
+ if (e.completed === !0 && t.length > 0) {
1375
+ const s = t.shift();
1376
+ clearTimeout(s.timer), s.resolve();
1377
+ return;
1378
+ }
1379
+ if (e.error && t.length > 0) {
1380
+ const s = t.shift();
1381
+ clearTimeout(s.timer), s.reject(new Error(`${e.command}: ${e.error}`));
1382
+ return;
1383
+ }
1384
+ }
1385
+ if (e.type === "log_line") {
1386
+ for (const t of this._logSubscribers)
1387
+ try {
1388
+ t.onLine({ timestamp: e.timestamp, line: e.line });
1389
+ } catch (s) {
1390
+ console.error("subscribeLogs onLine threw:", s);
1391
+ }
1392
+ return;
1393
+ }
1394
+ if (e.type === "log_stream_error") {
1395
+ for (const t of this._logSubscribers)
1396
+ if (typeof t.onError == "function")
1397
+ try {
1398
+ t.onError(e.error);
1399
+ } catch (s) {
1400
+ console.error("subscribeLogs onError threw:", s);
1401
+ }
1402
+ return;
1403
+ }
1404
+ if (e.state) {
1405
+ const t = e.state;
1406
+ t.head_pose && (this._robotState.head = t.head_pose.flat()), t.antennas && (this._robotState.antennas = [t.antennas[0], t.antennas[1]]), typeof t.body_yaw == "number" && (this._robotState.body_yaw = t.body_yaw), t.motor_mode && (this._robotState.motor_mode = t.motor_mode), typeof t.is_move_running == "boolean" && (this._robotState.is_move_running = t.is_move_running), this._emit("state", { ...this._robotState });
1407
+ }
1408
+ e.error && this._emit("error", { source: "robot", error: e.error });
1409
+ }
1410
+ /** Snap video playback to live edge if buffered lag exceeds 0.5 s. */
1411
+ _startLatencyMonitor(e) {
1412
+ this._latencyMonitorId && clearInterval(this._latencyMonitorId), this._latencyMonitorId = setInterval(() => {
1413
+ if (!e.srcObject || e.paused) return;
1414
+ const t = e.buffered;
1415
+ if (t.length > 0) {
1416
+ const s = t.end(t.length - 1), i = s - e.currentTime;
1417
+ i > 0.5 && (console.log(`Latency correction: was ${i.toFixed(2)}s behind`), e.currentTime = s - 0.1);
1418
+ }
1419
+ }, 2e3);
1420
+ }
1421
+ }
1422
+ export {
1423
+ O as R
1424
+ };
1425
+ //# sourceMappingURL=reachy-mini-sdk-CM-WMoGJ.js.map