@pollen-robotics/reachy-mini-sdk 1.7.3-main.5cd69ad

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