@coasys/ad4m-connect 0.13.1-staging.7 → 0.13.1-staging.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.js CHANGED
@@ -39,7 +39,7 @@ var __async = (__this, __arguments, generator) => {
39
39
  };
40
40
 
41
41
  // ../package.json
42
- var version = "0.13.1-staging.7";
42
+ var version = "0.13.1-staging.9";
43
43
 
44
44
  // src/utils.ts
45
45
  function isEmbedded() {
@@ -360,6 +360,10 @@ var LONG_METHODS = /* @__PURE__ */ new Set([
360
360
  "perspective.runInterpretationWithHarness",
361
361
  "runtime.restartHolochain"
362
362
  ]);
363
+ var OPENS_METHODS = /* @__PURE__ */ new Set([
364
+ "perspective.modelSubscribe",
365
+ "perspective.subscribeQuery"
366
+ ]);
363
367
  var RpcError = class extends Error {
364
368
  constructor(status, body) {
365
369
  super(`RPC error ${status}: ${body}`);
@@ -729,7 +733,14 @@ var ApiClient = class {
729
733
  signal?.removeEventListener("abort", onAbort);
730
734
  fn();
731
735
  };
736
+ const cancel = () => {
737
+ if (pending.sent && this._ws?.readyState === 1) {
738
+ this._send(this._ws, JSON.stringify({ id: nextId(), type: "request.cancel", params: { targetId: id } }));
739
+ }
740
+ };
732
741
  const timer = setTimeout(() => {
742
+ if (OPENS_METHODS.has(type))
743
+ cancel();
733
744
  settle(() => reject(new RpcError(408, `RPC call '${type}' timed out after ${timeoutMs}ms`)));
734
745
  if (this._ws?.readyState === 0 && this._pendingCalls.size === 0) {
735
746
  this._closeWs();
@@ -738,9 +749,7 @@ var ApiClient = class {
738
749
  }
739
750
  }, timeoutMs);
740
751
  const onAbort = () => {
741
- if (pending.sent && this._ws?.readyState === 1) {
742
- this._send(this._ws, JSON.stringify({ id: nextId(), type: "request.cancel", params: { targetId: id } }));
743
- }
752
+ cancel();
744
753
  settle(() => reject(new DOMException("Aborted", "AbortError")));
745
754
  };
746
755
  const pending = {
@@ -1117,6 +1126,7 @@ var AgentStatus = class {
1117
1126
  }
1118
1127
  }
1119
1128
  };
1129
+ var AGENT_KIND = "ad4m://agent_kind";
1120
1130
  var __classPrivateFieldSet$e = function(receiver, state, value, kind, f) {
1121
1131
  if (kind === "m")
1122
1132
  throw new TypeError("Private method is not writable");
@@ -1364,6 +1374,17 @@ var AgentClient = class {
1364
1374
  const kept = (perspective?.links ?? []).filter((link) => !removals.some((r) => linkEqual(link, r)));
1365
1375
  return this.updatePublicPerspective({ links: [...kept, ...added] });
1366
1376
  }
1377
+ async setKind(kind) {
1378
+ const me = await this.me();
1379
+ const said = (me.perspective?.links ?? []).filter((l) => l.data.source === me.did && l.data.predicate === AGENT_KIND);
1380
+ if (kind === null && said.length === 0 || said.length === 1 && said[0].data.target === kind) {
1381
+ return me;
1382
+ }
1383
+ return this.mutatePublicPerspective({
1384
+ additions: kind === null ? [] : [{ source: me.did, predicate: AGENT_KIND, target: kind }],
1385
+ removals: said
1386
+ });
1387
+ }
1367
1388
  async updateDirectMessageLanguage(directMessageLanguage) {
1368
1389
  const agent = toAgent(await __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").call("agent.updateProfile", { dmLanguage: directMessageLanguage }));
1369
1390
  __classPrivateFieldGet$d(this, _AgentClient_instances, "m", _AgentClient_cacheAgent).call(this, agent);
@@ -1689,32 +1710,36 @@ var NeighbourhoodClient = class {
1689
1710
  async sfuListRooms() {
1690
1711
  return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.listRooms", {});
1691
1712
  }
1692
- async sfuCallJoin(neighbourhoodUrl, roomName, sdpOffer) {
1713
+ async sfuCallJoin(neighbourhoodUrl, roomName, sdpOffer, deviceId, sessionKey) {
1693
1714
  return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.callJoin", {
1694
1715
  neighbourhoodUrl,
1695
1716
  roomName,
1696
- sdpOffer
1717
+ sdpOffer,
1718
+ deviceId,
1719
+ sessionKey
1697
1720
  });
1698
1721
  }
1699
- async sfuCallLeave(neighbourhoodUrl, roomName) {
1700
- return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.callLeave", { neighbourhoodUrl, roomName });
1722
+ async sfuCallLeave(neighbourhoodUrl, roomName, participantId) {
1723
+ return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.callLeave", { neighbourhoodUrl, roomName, participantId });
1701
1724
  }
1702
- async sfuCallSetQualityPreference(neighbourhoodUrl, roomName, preference) {
1725
+ async sfuCallSetQualityPreference(neighbourhoodUrl, roomName, participantId, preference) {
1703
1726
  return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.callSetQualityPreference", {
1704
1727
  neighbourhoodUrl,
1705
1728
  roomName,
1729
+ participantId,
1706
1730
  preference
1707
1731
  });
1708
1732
  }
1709
- async sfuCallAnswerServerOffer(neighbourhoodUrl, roomName, sdpAnswer) {
1733
+ async sfuCallAnswerServerOffer(neighbourhoodUrl, roomName, participantId, sdpAnswer) {
1710
1734
  return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.callAnswerServerOffer", {
1711
1735
  neighbourhoodUrl,
1712
1736
  roomName,
1737
+ participantId,
1713
1738
  sdpAnswer
1714
1739
  });
1715
1740
  }
1716
- async sfuCallRestartIce(neighbourhoodUrl, roomName) {
1717
- return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.callRestartIce", { neighbourhoodUrl, roomName });
1741
+ async sfuCallRestartIce(neighbourhoodUrl, roomName, participantId) {
1742
+ return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.callRestartIce", { neighbourhoodUrl, roomName, participantId });
1718
1743
  }
1719
1744
  onNetworkChange(callback) {
1720
1745
  return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").onNetworkChange(callback);
@@ -1734,17 +1759,19 @@ var NeighbourhoodClient = class {
1734
1759
  async sfuPeersForNeighbourhood(neighbourhoodUrl) {
1735
1760
  return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.sfuPeersForNeighbourhood", { neighbourhoodUrl });
1736
1761
  }
1737
- async sfuAddIceCandidate(neighbourhoodUrl, roomName, candidate) {
1762
+ async sfuAddIceCandidate(neighbourhoodUrl, roomName, participantId, candidate) {
1738
1763
  return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.addIceCandidate", {
1739
1764
  neighbourhoodUrl,
1740
1765
  roomName,
1766
+ participantId,
1741
1767
  candidate
1742
1768
  });
1743
1769
  }
1744
- async sfuSendData(neighbourhoodUrl, roomName, channelLabel, data, binary = false) {
1770
+ async sfuSendData(neighbourhoodUrl, roomName, participantId, channelLabel, data, binary = false) {
1745
1771
  return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.sendData", {
1746
1772
  neighbourhoodUrl,
1747
1773
  roomName,
1774
+ participantId,
1748
1775
  channelLabel,
1749
1776
  data,
1750
1777
  binary
@@ -1756,12 +1783,16 @@ var NeighbourhoodClient = class {
1756
1783
  subscribeSfuRoomRoster(callback) {
1757
1784
  return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").on("sfu-room-roster", (roster) => callback(roster));
1758
1785
  }
1786
+ subscribeSfuSessionReplaced(callback) {
1787
+ return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").on("sfu-session-replaced", (event) => callback(event));
1788
+ }
1759
1789
  subscribeSfuCallRenegotiationOffer(targetDid, callback) {
1760
1790
  return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").on("sfu-call-renegotiation-offer", (event) => {
1761
1791
  if (event.targetDid !== targetDid)
1762
1792
  return;
1763
1793
  callback({
1764
1794
  targetDid: event.targetDid,
1795
+ participantId: event.participantId,
1765
1796
  neighbourhoodUrl: event.neighbourhoodUrl,
1766
1797
  roomName: event.roomName,
1767
1798
  sdpOffer: event.sdpOffer,
@@ -1807,8 +1838,37 @@ _NeighbourhoodClient_apiClient = /* @__PURE__ */ new WeakMap(), _NeighbourhoodCl
1807
1838
  var DEFAULT_ICE_SERVERS$1 = [
1808
1839
  { urls: "stun:stun.l.google.com:19302" }
1809
1840
  ];
1841
+ var DEVICE_ID_KEY = "v1/ad4m-sfu-device-id";
1842
+ var processDeviceId = null;
1843
+ function randomId() {
1844
+ const crypto2 = globalThis.crypto;
1845
+ if (crypto2?.randomUUID)
1846
+ return crypto2.randomUUID();
1847
+ return Array.from({ length: 4 }, () => Math.random().toString(36).slice(2, 10)).join("");
1848
+ }
1849
+ function defaultDeviceId() {
1850
+ let storage;
1851
+ try {
1852
+ storage = globalThis.localStorage;
1853
+ } catch {
1854
+ storage = void 0;
1855
+ }
1856
+ if (storage) {
1857
+ try {
1858
+ let id = storage.getItem(DEVICE_ID_KEY);
1859
+ if (!id) {
1860
+ id = randomId();
1861
+ storage.setItem(DEVICE_ID_KEY, id);
1862
+ }
1863
+ return id;
1864
+ } catch {
1865
+ }
1866
+ }
1867
+ return processDeviceId ?? (processDeviceId = randomId());
1868
+ }
1810
1869
  var SfuManager = class {
1811
- constructor(neighbourhood, roomId, agentDid, neighbourhoodUrl, iceConfig, sfuConfig) {
1870
+ constructor(neighbourhood, roomId, agentDid, neighbourhoodUrl, iceConfig, sfuConfig, deviceId) {
1871
+ this.sessionKey = randomId();
1812
1872
  this.callbacks = /* @__PURE__ */ new Map();
1813
1873
  this.reconnectAttempts = 0;
1814
1874
  this.reconnecting = false;
@@ -1822,6 +1882,9 @@ var SfuManager = class {
1822
1882
  this.answeredOffer = null;
1823
1883
  this.renegotiationUnsubscribe = null;
1824
1884
  this.rosterUnsubscribe = null;
1885
+ this.replacedUnsubscribe = null;
1886
+ this.heldIds = /* @__PURE__ */ new Set();
1887
+ this.joinSettled = Promise.resolve();
1825
1888
  this.dataChannelUnsubscribe = null;
1826
1889
  this.restartTimer = null;
1827
1890
  this.networkUnsubscribe = null;
@@ -1830,6 +1893,7 @@ var SfuManager = class {
1830
1893
  this.neighbourhoodUrl = neighbourhoodUrl || "";
1831
1894
  this.roomId = roomId;
1832
1895
  this.agentDid = agentDid;
1896
+ this.deviceId = deviceId || defaultDeviceId();
1833
1897
  this.state = {
1834
1898
  topology: "sfu",
1835
1899
  roomId,
@@ -1863,6 +1927,7 @@ var SfuManager = class {
1863
1927
  console.info(`SFU: connection failed, reconnecting (${this.reconnectAttempts}/${SfuManager.MAX_RECONNECTS})`);
1864
1928
  this.reconnecting = true;
1865
1929
  this.endRestart();
1930
+ const previous = this.state.participantId;
1866
1931
  try {
1867
1932
  const deadline = Date.now() + SfuManager.REJOIN_WINDOW_MS;
1868
1933
  for (let delay = 1e3; ; delay = Math.min(delay * 2, 1e4)) {
@@ -1871,10 +1936,7 @@ var SfuManager = class {
1871
1936
  this.state.peerConnection.close();
1872
1937
  this.state.peerConnection = null;
1873
1938
  }
1874
- try {
1875
- await this.neighbourhood.sfuCallLeave(this.neighbourhoodUrl, this.roomId);
1876
- } catch {
1877
- }
1939
+ await this.leaveSession();
1878
1940
  if (generation !== this.generation)
1879
1941
  return;
1880
1942
  this.resetParticipants();
@@ -1886,6 +1948,15 @@ var SfuManager = class {
1886
1948
  } catch (e) {
1887
1949
  if (generation !== this.generation)
1888
1950
  return;
1951
+ if (e instanceof RpcError && e.status === 409) {
1952
+ this.stopReplaced({
1953
+ targetDid: this.agentDid,
1954
+ neighbourhoodUrl: this.neighbourhoodUrl,
1955
+ roomName: this.roomId,
1956
+ participantId: previous ?? ""
1957
+ });
1958
+ return;
1959
+ }
1889
1960
  if (Date.now() + delay > deadline) {
1890
1961
  console.error("SFU reconnect failed:", e);
1891
1962
  this.emit("error", e);
@@ -1902,18 +1973,20 @@ var SfuManager = class {
1902
1973
  }
1903
1974
  }
1904
1975
  restartIce(pc) {
1905
- if (this.restartTimer || this.reconnecting || this.state.peerConnection !== pc)
1976
+ const participantId = this.state.participantId;
1977
+ if (this.restartTimer || this.reconnecting || this.state.peerConnection !== pc || !participantId)
1906
1978
  return;
1979
+ const generation = this.generation;
1907
1980
  console.info("SFU: restarting ICE");
1908
1981
  this.restartTimer = setTimeout(() => {
1909
1982
  this.restartTimer = null;
1910
- if (this.state.peerConnection !== pc)
1983
+ if (generation !== this.generation || this.state.peerConnection !== pc)
1911
1984
  return;
1912
1985
  if (pc.iceConnectionState === "connected" || pc.iceConnectionState === "completed")
1913
1986
  return;
1914
1987
  void this.reconnect();
1915
1988
  }, SfuManager.RESTART_TIMEOUT_MS);
1916
- this.neighbourhood.sfuCallRestartIce(this.neighbourhoodUrl, this.roomId).catch((err2) => {
1989
+ this.neighbourhood.sfuCallRestartIce(this.neighbourhoodUrl, this.roomId, participantId).catch((err2) => {
1917
1990
  console.warn("SFU: ICE restart refused:", err2);
1918
1991
  });
1919
1992
  }
@@ -1956,6 +2029,9 @@ var SfuManager = class {
1956
2029
  }
1957
2030
  }
1958
2031
  async join(localStream) {
2032
+ const generation = this.generation;
2033
+ if (!this.reconnecting)
2034
+ this.sessionKey = randomId();
1959
2035
  this.state.localStream = localStream;
1960
2036
  const pc = new RTCPeerConnection({ iceServers: this.iceServers });
1961
2037
  this.state.peerConnection = pc;
@@ -2002,10 +2078,10 @@ var SfuManager = class {
2002
2078
  if (this.state.peerConnection !== pc)
2003
2079
  return;
2004
2080
  const mid = event.transceiver?.mid;
2005
- const did = mid ? this.midToParticipant.get(mid) : void 0;
2006
- if (!did || did === this.agentDid || this.departed.has(did))
2081
+ const owner = mid ? this.midToParticipant.get(mid) : void 0;
2082
+ if (!owner || owner.participantId === this.state.participantId || this.departed.has(owner.participantId))
2007
2083
  return;
2008
- const participant = this.ensureParticipant(did);
2084
+ const participant = this.ensureParticipant(owner.participantId, owner.did);
2009
2085
  participant.stream.addTrack(event.track);
2010
2086
  this.refreshKinds(participant);
2011
2087
  this.emit("stream-added", participant.stream, event.track);
@@ -2021,7 +2097,9 @@ var SfuManager = class {
2021
2097
  if (!event.candidate)
2022
2098
  return;
2023
2099
  if (joinComplete) {
2024
- this.neighbourhood.sfuAddIceCandidate(this.neighbourhoodUrl, this.roomId, event.candidate.candidate).catch((err2) => {
2100
+ if (this.state.peerConnection !== pc || !this.state.participantId)
2101
+ return;
2102
+ this.neighbourhood.sfuAddIceCandidate(this.neighbourhoodUrl, this.roomId, this.state.participantId, event.candidate.candidate).catch((err2) => {
2025
2103
  console.error("SFU: failed to trickle ICE candidate:", err2);
2026
2104
  });
2027
2105
  } else {
@@ -2035,29 +2113,43 @@ var SfuManager = class {
2035
2113
  const joined = new Promise((resolve) => {
2036
2114
  markJoined = resolve;
2037
2115
  });
2116
+ this.joinSettled = joined;
2038
2117
  this.subscribeServerEvents(pc, joined);
2039
2118
  let session;
2040
2119
  try {
2041
- session = await this.neighbourhood.sfuCallJoin(this.neighbourhoodUrl, this.roomId, sdpOffer);
2120
+ session = await this.neighbourhood.sfuCallJoin(this.neighbourhoodUrl, this.roomId, sdpOffer, this.deviceId, this.sessionKey);
2042
2121
  } catch (err2) {
2043
2122
  markJoined();
2044
2123
  this.abandon(pc);
2045
2124
  throw err2;
2046
2125
  }
2126
+ if (generation !== this.generation) {
2127
+ markJoined();
2128
+ this.abandon(pc);
2129
+ await this.neighbourhood.sfuCallLeave(this.neighbourhoodUrl, this.roomId, session.participantId).catch((e) => console.warn("SFU: leaving the call failed:", e));
2130
+ return;
2131
+ }
2047
2132
  this.state.participantId = session.participantId;
2133
+ this.heldIds.add(session.participantId);
2048
2134
  try {
2049
2135
  const answer = JSON.parse(session.sdpAnswer);
2050
2136
  await pc.setRemoteDescription(new RTCSessionDescription(answer));
2051
2137
  } catch (err2) {
2052
2138
  markJoined();
2139
+ if (generation !== this.generation)
2140
+ return;
2053
2141
  this.abandon(pc);
2142
+ await this.leaveSession();
2054
2143
  throw err2;
2055
2144
  }
2056
2145
  markJoined();
2057
- this.applyRoster(session.streamMapping.map((entry) => entry.slice(entry.indexOf(":") + 1)), false);
2146
+ this.applyRoster(session.streamMapping.map((entry) => {
2147
+ const at = entry.indexOf(":");
2148
+ return { participantId: entry.slice(0, at), agentDid: entry.slice(at + 1) };
2149
+ }), false);
2058
2150
  joinComplete = true;
2059
2151
  for (const candidate of pendingCandidates) {
2060
- this.neighbourhood.sfuAddIceCandidate(this.neighbourhoodUrl, this.roomId, candidate).catch((err2) => {
2152
+ this.neighbourhood.sfuAddIceCandidate(this.neighbourhoodUrl, this.roomId, session.participantId, candidate).catch((err2) => {
2061
2153
  console.error("SFU: failed to trickle buffered ICE candidate:", err2);
2062
2154
  });
2063
2155
  }
@@ -2075,8 +2167,9 @@ var SfuManager = class {
2075
2167
  this.unlistedTimer = null;
2076
2168
  }
2077
2169
  }
2078
- noticeRoster(pc, dids) {
2079
- if (dids.includes(this.agentDid)) {
2170
+ noticeRoster(pc, sessions) {
2171
+ const participantId = this.state.participantId;
2172
+ if (!participantId || sessions.some((s) => s.participantId === participantId)) {
2080
2173
  this.clearUnlistedTimer();
2081
2174
  return;
2082
2175
  }
@@ -2084,14 +2177,32 @@ var SfuManager = class {
2084
2177
  return;
2085
2178
  this.unlistedTimer = setTimeout(() => {
2086
2179
  this.unlistedTimer = null;
2087
- if (this.state.peerConnection !== pc)
2180
+ if (this.state.peerConnection !== pc || this.state.participantId !== participantId)
2088
2181
  return;
2089
2182
  console.info("SFU: the room no longer lists this session, rebuilding the call");
2090
2183
  void this.reconnect();
2091
2184
  }, SfuManager.UNLISTED_GRACE_MS);
2092
2185
  }
2186
+ async leaveSession() {
2187
+ const participantId = this.state.participantId;
2188
+ if (!participantId)
2189
+ return;
2190
+ this.state.participantId = null;
2191
+ let found = true;
2192
+ try {
2193
+ found = await this.neighbourhood.sfuCallLeave(this.neighbourhoodUrl, this.roomId, participantId);
2194
+ } catch (e) {
2195
+ console.warn("SFU: leaving the call failed:", e);
2196
+ }
2197
+ if (found)
2198
+ this.heldIds.delete(participantId);
2199
+ }
2093
2200
  abandon(pc) {
2094
2201
  this.releaseServerEvents();
2202
+ if (this.heldIds.size === 0) {
2203
+ this.replacedUnsubscribe?.();
2204
+ this.replacedUnsubscribe = null;
2205
+ }
2095
2206
  pc.close();
2096
2207
  if (this.state.peerConnection === pc)
2097
2208
  this.state.peerConnection = null;
@@ -2102,7 +2213,10 @@ var SfuManager = class {
2102
2213
  this.renegotiationUnsubscribe = this.neighbourhood.subscribeSfuCallRenegotiationOffer(this.agentDid, (event) => {
2103
2214
  if (!ours(event))
2104
2215
  return;
2105
- this.offerQueue = this.offerQueue.then(() => joined).then(() => this.applyServerOffer(pc, event));
2216
+ this.offerQueue = this.offerQueue.then(() => joined).then(() => {
2217
+ if (event.participantId === this.state.participantId)
2218
+ return this.applyServerOffer(pc, event);
2219
+ });
2106
2220
  });
2107
2221
  this.rosterUnsubscribe = this.neighbourhood.subscribeSfuRoomRoster((roster) => {
2108
2222
  if (!ours(roster) || this.state.peerConnection !== pc)
@@ -2114,6 +2228,16 @@ var SfuManager = class {
2114
2228
  this.noticeRoster(pc, roster.participants);
2115
2229
  });
2116
2230
  });
2231
+ this.replacedUnsubscribe ?? (this.replacedUnsubscribe = this.neighbourhood.subscribeSfuSessionReplaced((event) => {
2232
+ if (!ours(event))
2233
+ return;
2234
+ const stopIfHeld = () => {
2235
+ if (this.heldIds.has(event.participantId))
2236
+ this.stopReplaced(event);
2237
+ };
2238
+ stopIfHeld();
2239
+ void this.joinSettled.then(stopIfHeld);
2240
+ }));
2117
2241
  for (const unsubscribe of previous)
2118
2242
  unsubscribe?.();
2119
2243
  }
@@ -2121,12 +2245,12 @@ var SfuManager = class {
2121
2245
  if (this.state.peerConnection !== pc || event.sdpOffer === this.answeredOffer)
2122
2246
  return;
2123
2247
  for (const entry of event.trackMapping ?? []) {
2124
- this.midToParticipant.set(entry.mid, entry.agentDid);
2248
+ this.midToParticipant.set(entry.mid, { participantId: entry.participantId, did: entry.agentDid });
2125
2249
  }
2126
2250
  try {
2127
2251
  await pc.setRemoteDescription(new RTCSessionDescription(JSON.parse(event.sdpOffer)));
2128
2252
  await pc.setLocalDescription(await pc.createAnswer());
2129
- await this.neighbourhood.sfuCallAnswerServerOffer(this.neighbourhoodUrl, event.roomName, JSON.stringify(pc.localDescription));
2253
+ await this.neighbourhood.sfuCallAnswerServerOffer(this.neighbourhoodUrl, event.roomName, event.participantId, JSON.stringify(pc.localDescription));
2130
2254
  this.answeredOffer = event.sdpOffer;
2131
2255
  } catch (err2) {
2132
2256
  if (this.state.peerConnection !== pc)
@@ -2135,48 +2259,58 @@ var SfuManager = class {
2135
2259
  void this.reconnect();
2136
2260
  }
2137
2261
  }
2138
- applyRoster(dids, complete) {
2139
- const present = new Set(dids.filter((did) => did !== this.agentDid));
2140
- for (const did of present) {
2141
- this.departed.delete(did);
2142
- this.ensureParticipant(did);
2262
+ applyRoster(sessions, complete) {
2263
+ const present = sessions.filter((s) => s.participantId !== this.state.participantId);
2264
+ for (const { participantId, agentDid } of present) {
2265
+ this.departed.delete(participantId);
2266
+ this.ensureParticipant(participantId, agentDid);
2143
2267
  }
2144
2268
  if (!complete)
2145
2269
  return;
2146
- for (const [did, participant] of [...this.state.participants]) {
2147
- if (present.has(did))
2270
+ const listed = new Set(present.map((s) => s.participantId));
2271
+ for (const [participantId, participant] of [...this.state.participants]) {
2272
+ if (listed.has(participantId))
2148
2273
  continue;
2149
- this.state.participants.delete(did);
2150
- this.departed.add(did);
2274
+ this.state.participants.delete(participantId);
2275
+ this.departed.add(participantId);
2151
2276
  for (const [mid, owner] of this.midToParticipant) {
2152
- if (owner === did)
2277
+ if (owner.participantId === participantId)
2153
2278
  this.midToParticipant.delete(mid);
2154
2279
  }
2155
2280
  this.emit("participant-left", participant);
2156
2281
  }
2157
2282
  }
2158
- ensureParticipant(did) {
2159
- let participant = this.state.participants.get(did);
2283
+ ensureParticipant(participantId, did) {
2284
+ let participant = this.state.participants.get(participantId);
2160
2285
  if (!participant) {
2161
2286
  participant = {
2287
+ participantId,
2162
2288
  did,
2163
2289
  stream: new MediaStream(),
2164
2290
  hasAudio: false,
2165
2291
  hasVideo: false,
2166
2292
  isActiveSpeaker: false
2167
2293
  };
2168
- this.state.participants.set(did, participant);
2294
+ this.state.participants.set(participantId, participant);
2169
2295
  this.emit("participant-joined", participant);
2170
2296
  }
2171
2297
  return participant;
2172
2298
  }
2173
- refreshKinds(participant) {
2174
- participant.hasAudio = participant.stream.getAudioTracks().length > 0;
2175
- participant.hasVideo = participant.stream.getVideoTracks().length > 0;
2299
+ stopReplaced(event) {
2300
+ console.info("SFU: another tab on this device joined the call; this one stops");
2301
+ if (this.state.participantId === event.participantId)
2302
+ this.state.participantId = null;
2303
+ this.stop();
2304
+ void this.leaveSession();
2305
+ this.resetParticipants();
2306
+ this.emit("replaced", event);
2176
2307
  }
2177
- async leave() {
2308
+ stop() {
2178
2309
  this.generation++;
2179
2310
  this.releaseServerEvents();
2311
+ this.replacedUnsubscribe?.();
2312
+ this.replacedUnsubscribe = null;
2313
+ this.heldIds.clear();
2180
2314
  this.endRestart();
2181
2315
  this.networkUnsubscribe?.();
2182
2316
  this.networkUnsubscribe = null;
@@ -2194,11 +2328,15 @@ var SfuManager = class {
2194
2328
  this.state.peerConnection.close();
2195
2329
  this.state.peerConnection = null;
2196
2330
  }
2197
- try {
2198
- await this.neighbourhood.sfuCallLeave(this.neighbourhoodUrl, this.roomId);
2199
- } catch (e) {
2200
- console.error("Error leaving SFU call:", e);
2201
- }
2331
+ this.state.localStream = null;
2332
+ }
2333
+ refreshKinds(participant) {
2334
+ participant.hasAudio = participant.stream.getAudioTracks().length > 0;
2335
+ participant.hasVideo = participant.stream.getVideoTracks().length > 0;
2336
+ }
2337
+ async leave() {
2338
+ this.stop();
2339
+ await this.leaveSession();
2202
2340
  this.resetParticipants();
2203
2341
  }
2204
2342
  resetParticipants() {
@@ -2206,7 +2344,6 @@ var SfuManager = class {
2206
2344
  this.emit("participant-left", participant);
2207
2345
  }
2208
2346
  this.state.participants.clear();
2209
- this.state.participantId = null;
2210
2347
  this.midToParticipant.clear();
2211
2348
  this.departed.clear();
2212
2349
  }
@@ -2217,7 +2354,7 @@ var SfuManager = class {
2217
2354
  return;
2218
2355
  }
2219
2356
  try {
2220
- await this.neighbourhood.sfuCallSetQualityPreference(this.neighbourhoodUrl, this.roomId, preference);
2357
+ await this.neighbourhood.sfuCallSetQualityPreference(this.neighbourhoodUrl, this.roomId, this.state.participantId, preference);
2221
2358
  } catch (e) {
2222
2359
  console.error("Failed to set quality preference:", e);
2223
2360
  this.emit("error", e);
@@ -2240,7 +2377,7 @@ var SfuManager = class {
2240
2377
  return;
2241
2378
  }
2242
2379
  try {
2243
- await this.neighbourhood.sfuSendData(this.neighbourhoodUrl, this.roomId, channelLabel, data, binary);
2380
+ await this.neighbourhood.sfuSendData(this.neighbourhoodUrl, this.roomId, this.state.participantId, channelLabel, data, binary);
2244
2381
  } catch (e) {
2245
2382
  console.error("SFU: sendData failed:", e);
2246
2383
  this.emit("error", e);
@@ -2253,7 +2390,11 @@ var SfuManager = class {
2253
2390
  } catch {
2254
2391
  }
2255
2392
  }
2256
- this.dataChannelUnsubscribe = this.neighbourhood.subscribeSfuDataChannel(callback);
2393
+ this.dataChannelUnsubscribe = this.neighbourhood.subscribeSfuDataChannel((message) => {
2394
+ if (message.senderParticipantId && message.senderParticipantId === this.state.participantId)
2395
+ return;
2396
+ callback(message);
2397
+ });
2257
2398
  return () => {
2258
2399
  if (this.dataChannelUnsubscribe) {
2259
2400
  try {
@@ -2327,9 +2468,23 @@ function parseCallMessage(payload) {
2327
2468
  }
2328
2469
  var RTC_PREDICATE = "ad4m://session/rtc";
2329
2470
  var TARGET_ALL = "*";
2330
- function createTelepresenceChannel(proxy, selfDid) {
2471
+ function meshPeerId(did, device) {
2472
+ if (!isMeshDevice(device))
2473
+ throw new Error(`mesh: device id must be non-empty and without '#': ${JSON.stringify(device)}`);
2474
+ return `${did}#${device}`;
2475
+ }
2476
+ function isMeshDevice(device) {
2477
+ return typeof device === "string" && device.length > 0 && !device.includes("#");
2478
+ }
2479
+ function agentOfMeshPeer(peerId) {
2480
+ const at = peerId.lastIndexOf("#");
2481
+ return at === -1 ? peerId : peerId.slice(0, at);
2482
+ }
2483
+ function createTelepresenceChannel(proxy, selfDid, selfDevice) {
2484
+ const self = meshPeerId(selfDid, selfDevice);
2331
2485
  const resultListeners = /* @__PURE__ */ new Set();
2332
2486
  let subscribed = Promise.resolve();
2487
+ let warnedNoDevice = false;
2333
2488
  const report = (result) => {
2334
2489
  for (const cb of resultListeners) {
2335
2490
  try {
@@ -2346,7 +2501,7 @@ function createTelepresenceChannel(proxy, selfDid) {
2346
2501
  try {
2347
2502
  sent = proxy.sendBroadcastU({
2348
2503
  links: [{
2349
- source: JSON.stringify(payload),
2504
+ source: JSON.stringify({ device: selfDevice, message: payload }),
2350
2505
  predicate: RTC_PREDICATE,
2351
2506
  target: to?.agentId ?? TARGET_ALL
2352
2507
  }]
@@ -2371,9 +2526,7 @@ function createTelepresenceChannel(proxy, selfDid) {
2371
2526
  const { source, predicate, target } = link.data ?? {};
2372
2527
  if (typeof predicate !== "string" || predicate !== RTC_PREDICATE)
2373
2528
  return;
2374
- if (target && target !== TARGET_ALL && target !== selfDid)
2375
- return;
2376
- if (link.author === selfDid)
2529
+ if (target && target !== TARGET_ALL && target !== self)
2377
2530
  return;
2378
2531
  let parsed;
2379
2532
  try {
@@ -2381,7 +2534,20 @@ function createTelepresenceChannel(proxy, selfDid) {
2381
2534
  } catch {
2382
2535
  return;
2383
2536
  }
2384
- cb(link.author, parsed);
2537
+ if (typeof parsed !== "object" || parsed === null)
2538
+ return;
2539
+ const { device, message } = parsed;
2540
+ if (!isMeshDevice(device)) {
2541
+ if (device === void 0 && !warnedNoDevice) {
2542
+ warnedNoDevice = true;
2543
+ console.warn(`mesh: ${link.author} sends no device id (an older SDK); its mesh messages are ignored`);
2544
+ }
2545
+ return;
2546
+ }
2547
+ const from = meshPeerId(link.author, device);
2548
+ if (from === self)
2549
+ return;
2550
+ cb(from, message);
2385
2551
  };
2386
2552
  subscribed = proxy.addSignalHandler(handler).catch((err2) => {
2387
2553
  console.warn("mesh: signal handler registration failed \u2014 inbound traffic will get missed:", err2);
@@ -2521,6 +2687,8 @@ var MeshManager = class {
2521
2687
  this.enqueue(from, slot, message);
2522
2688
  });
2523
2689
  await this.channel.listening?.();
2690
+ if (this.closed)
2691
+ return;
2524
2692
  this.publish({ v: CALL_PROTOCOL_VERSION, call: this.callId, warm: true });
2525
2693
  if (this.sweepMs > 0)
2526
2694
  this.sweep = setInterval(() => this.tick(), this.sweepMs);
@@ -2638,6 +2806,7 @@ var MeshManager = class {
2638
2806
  handleData(from, message) {
2639
2807
  const msg = {
2640
2808
  senderDid: from,
2809
+ senderParticipantId: from,
2641
2810
  neighbourhoodUrl: "",
2642
2811
  roomName: this.callId,
2643
2812
  channelLabel: message.label,
@@ -3057,8 +3226,28 @@ var MeshManager = class {
3057
3226
  };
3058
3227
  var CALL_PRESENCE_PREDICATE = "ad4m://session/in-call";
3059
3228
  var ROSTER_POLL_INTERVAL_MS = 3e3;
3229
+ function presencePeer(did, link, roomId) {
3230
+ if (link?.predicate !== CALL_PRESENCE_PREDICATE || link.target !== roomId)
3231
+ return null;
3232
+ const source = link.source;
3233
+ if (typeof source !== "string" || source === did || agentOfMeshPeer(source) !== did)
3234
+ return null;
3235
+ return source;
3236
+ }
3237
+ function sameDeviceChannel(agentDid, device, roomId) {
3238
+ const Channel = globalThis.BroadcastChannel;
3239
+ if (typeof Channel !== "function")
3240
+ return null;
3241
+ try {
3242
+ return new Channel(`ad4m-call:${agentDid}:${device}:${roomId}`);
3243
+ } catch {
3244
+ return null;
3245
+ }
3246
+ }
3060
3247
  function createSession(config) {
3061
- const { api, roomId, agentDid, neighbourhoodUrl, topology, sfuConfig, iceServers, channel, setOnlineStatus, ownOnlineStatus, onlineAgents, localSfuStatus, sfuServesAllMembers } = config;
3248
+ const { api, roomId, agentDid, neighbourhoodUrl, topology, sfuConfig, iceServers, deviceId, channel, setOnlineStatus, ownOnlineStatus, onlineAgents, localSfuStatus, sfuServesAllMembers } = config;
3249
+ const device = deviceId || defaultDeviceId();
3250
+ const selfPeer = meshPeerId(agentDid, device);
3062
3251
  let state = "idle";
3063
3252
  let sfuManager = null;
3064
3253
  let meshManager = null;
@@ -3068,6 +3257,7 @@ function createSession(config) {
3068
3257
  const trackListeners = [];
3069
3258
  const dataListeners = [];
3070
3259
  let dataUnsubscribe = null;
3260
+ let sameDevice = null;
3071
3261
  function emit(event, ...args) {
3072
3262
  const cbs = callbacks.get(event);
3073
3263
  if (cbs)
@@ -3078,6 +3268,10 @@ function createSession(config) {
3078
3268
  state = next;
3079
3269
  emit("state-changed", next);
3080
3270
  }
3271
+ let destroying = false;
3272
+ function destroyed() {
3273
+ return destroying || state === "closed";
3274
+ }
3081
3275
  async function resolveTopology() {
3082
3276
  if (topology === "sfu")
3083
3277
  return "sfu";
@@ -3104,7 +3298,7 @@ function createSession(config) {
3104
3298
  const l = link.data;
3105
3299
  if (!l?.source || l.target === void 0)
3106
3300
  continue;
3107
- if (l.predicate === CALL_PRESENCE_PREDICATE && l.target === roomId)
3301
+ if (presencePeer(agentDid, l, roomId) === selfPeer)
3108
3302
  continue;
3109
3303
  links.push({ source: l.source, target: l.target, ...l.predicate ? { predicate: l.predicate } : {} });
3110
3304
  }
@@ -3118,7 +3312,7 @@ function createSession(config) {
3118
3312
  console.warn("session: reading own status failed:", err2);
3119
3313
  return [];
3120
3314
  });
3121
- const presence = { source: agentDid, predicate: CALL_PRESENCE_PREDICATE, target: roomId };
3315
+ const presence = { source: selfPeer, predicate: CALL_PRESENCE_PREDICATE, target: roomId };
3122
3316
  await setOnlineStatus({ links: [...statusBeforeCall, presence] });
3123
3317
  announced = true;
3124
3318
  } catch (err2) {
@@ -3146,21 +3340,23 @@ function createSession(config) {
3146
3340
  polling = true;
3147
3341
  try {
3148
3342
  const agents = await onlineAgents();
3343
+ const own = ownOnlineStatus ? await ownOnlineStatus() : null;
3149
3344
  if (meshManager !== mesh)
3150
3345
  return;
3151
- const inCall = [];
3152
- for (const agent of agents) {
3153
- if (agent.did === agentDid)
3154
- continue;
3155
- for (const link of agent.status?.data?.links ?? []) {
3156
- const l = link.data;
3157
- if (l?.predicate === CALL_PRESENCE_PREDICATE && l.target === roomId) {
3158
- inCall.push(agent.did);
3159
- break;
3160
- }
3346
+ const inCall = /* @__PURE__ */ new Set();
3347
+ const collect = (did, links) => {
3348
+ for (const link of links ?? []) {
3349
+ const peer = presencePeer(did, link.data, roomId);
3350
+ if (peer && peer !== selfPeer)
3351
+ inCall.add(peer);
3161
3352
  }
3353
+ };
3354
+ for (const agent of agents) {
3355
+ if (agent.did !== agentDid)
3356
+ collect(agent.did, agent.status?.data?.links);
3162
3357
  }
3163
- mesh.setRoster(inCall);
3358
+ collect(agentDid, own?.data?.links);
3359
+ mesh.setRoster([...inCall]);
3164
3360
  } catch (err2) {
3165
3361
  console.warn("session: roster poll failed:", err2);
3166
3362
  } finally {
@@ -3178,9 +3374,12 @@ function createSession(config) {
3178
3374
  }
3179
3375
  }
3180
3376
  function wireMeshEvents(mesh) {
3181
- for (const event of ["participant-joined", "participant-left", "participant-updated", "peer-state", "peer-recovery", "error"]) {
3377
+ for (const event of ["peer-state", "peer-recovery", "error"]) {
3182
3378
  mesh.on(event, (...args) => emit(event, ...args));
3183
3379
  }
3380
+ for (const event of ["participant-joined", "participant-left", "participant-updated"]) {
3381
+ mesh.on(event, (p) => emit(event, { ...p, participantId: p.did, did: agentOfMeshPeer(p.did) }));
3382
+ }
3184
3383
  mesh.on("stream-added", (stream, track) => {
3185
3384
  emit("stream-added", stream, track);
3186
3385
  for (const cb of trackListeners)
@@ -3190,18 +3389,68 @@ function createSession(config) {
3190
3389
  emit("stream-removed", stream, track);
3191
3390
  });
3192
3391
  }
3392
+ let replacedMesh = null;
3393
+ function claimDevice(mesh) {
3394
+ sameDevice = sameDeviceChannel(agentDid, device, roomId);
3395
+ if (!sameDevice)
3396
+ return;
3397
+ const channel2 = sameDevice;
3398
+ channel2.onmessage = (event) => {
3399
+ if (meshManager !== mesh || event.data?.joined !== true)
3400
+ return;
3401
+ replacedMesh = mesh;
3402
+ releaseDevice();
3403
+ stopRosterPolling();
3404
+ if (dataUnsubscribe) {
3405
+ dataUnsubscribe();
3406
+ dataUnsubscribe = null;
3407
+ }
3408
+ meshManager = null;
3409
+ announced = false;
3410
+ void mesh.leave();
3411
+ setState("idle");
3412
+ emit("replaced", { targetDid: agentDid, neighbourhoodUrl, roomName: roomId, participantId: selfPeer });
3413
+ };
3414
+ channel2.postMessage({ joined: true });
3415
+ }
3416
+ function releaseDevice() {
3417
+ if (!sameDevice)
3418
+ return;
3419
+ sameDevice.onmessage = null;
3420
+ sameDevice.close();
3421
+ sameDevice = null;
3422
+ }
3193
3423
  function wireSfuEvents(sfu) {
3424
+ const current = () => sfuManager === sfu;
3194
3425
  for (const event of ["topology-changed", "participant-joined", "participant-left", "active-speaker", "error"]) {
3195
- sfu.on(event, (...args) => emit(event, ...args));
3426
+ sfu.on(event, (...args) => {
3427
+ if (current())
3428
+ emit(event, ...args);
3429
+ });
3196
3430
  }
3197
3431
  sfu.on("stream-added", (stream, track) => {
3432
+ if (!current())
3433
+ return;
3198
3434
  emit("stream-added", stream, track);
3199
3435
  for (const cb of trackListeners)
3200
3436
  cb(stream, track);
3201
3437
  });
3202
3438
  sfu.on("stream-removed", (stream, track) => {
3439
+ if (!current())
3440
+ return;
3203
3441
  emit("stream-removed", stream, track);
3204
3442
  });
3443
+ sfu.on("replaced", (event) => {
3444
+ if (sfuManager !== sfu)
3445
+ return;
3446
+ if (dataUnsubscribe) {
3447
+ dataUnsubscribe();
3448
+ dataUnsubscribe = null;
3449
+ }
3450
+ sfuManager = null;
3451
+ setState("idle");
3452
+ emit("replaced", event);
3453
+ });
3205
3454
  }
3206
3455
  const session = {
3207
3456
  async join(localStream) {
@@ -3211,6 +3460,8 @@ function createSession(config) {
3211
3460
  throw new Error("Session already active");
3212
3461
  setState("joining");
3213
3462
  const topo = await resolveTopology();
3463
+ if (destroyed())
3464
+ throw new Error("Session destroyed");
3214
3465
  if (topo === "mesh") {
3215
3466
  if (!channel) {
3216
3467
  throw new Error("Mesh topology requires a signalling channel \u2014 pass a channel via SessionImplConfig or use topology 'sfu'");
@@ -3236,7 +3487,7 @@ function createSession(config) {
3236
3487
  const mesh = new MeshManager({
3237
3488
  channel,
3238
3489
  callId: roomId,
3239
- selfId: agentDid,
3490
+ selfId: selfPeer,
3240
3491
  ...meshIce.length > 0 ? { iceServers: meshIce } : {},
3241
3492
  onNetworkChange: (cb) => api.onNetworkChange(cb),
3242
3493
  checkConnection: () => api.checkConnection()
@@ -3247,21 +3498,39 @@ function createSession(config) {
3247
3498
  for (const cb of dataListeners)
3248
3499
  cb(msg);
3249
3500
  });
3501
+ claimDevice(mesh);
3250
3502
  await mesh.join(localStream);
3503
+ if (replacedMesh === mesh)
3504
+ return;
3505
+ if (destroyed())
3506
+ throw new Error("Session destroyed");
3251
3507
  await announceCallPresence();
3508
+ if (replacedMesh === mesh) {
3509
+ announced = false;
3510
+ return;
3511
+ }
3512
+ if (destroyed()) {
3513
+ await withdrawCallPresence();
3514
+ throw new Error("Session destroyed");
3515
+ }
3252
3516
  startRosterPolling();
3253
3517
  emit("topology-changed", "mesh");
3254
3518
  setState("active");
3255
3519
  return;
3256
3520
  }
3257
3521
  const iceConfig = iceServers && iceServers.length > 0 ? { servers: iceServers.map((s) => ({ urls: s.urls, ...s.username ? { username: s.username } : {}, ...s.credential ? { credential: s.credential } : {} })) } : void 0;
3258
- sfuManager = new SfuManager(api, roomId, agentDid, neighbourhoodUrl, iceConfig, sfuConfig);
3259
- wireSfuEvents(sfuManager);
3260
- dataUnsubscribe = sfuManager.subscribeDataChannel((msg) => {
3522
+ const manager = new SfuManager(api, roomId, agentDid, neighbourhoodUrl, iceConfig, sfuConfig, device);
3523
+ sfuManager = manager;
3524
+ wireSfuEvents(manager);
3525
+ dataUnsubscribe = manager.subscribeDataChannel((msg) => {
3261
3526
  for (const cb of dataListeners)
3262
3527
  cb(msg);
3263
3528
  });
3264
- await sfuManager.join(localStream);
3529
+ await manager.join(localStream);
3530
+ if (destroyed())
3531
+ throw new Error("Session destroyed");
3532
+ if (sfuManager !== manager)
3533
+ return;
3265
3534
  emit("topology-changed", "sfu");
3266
3535
  setState("active");
3267
3536
  },
@@ -3270,6 +3539,7 @@ function createSession(config) {
3270
3539
  return;
3271
3540
  setState("leaving");
3272
3541
  stopRosterPolling();
3542
+ releaseDevice();
3273
3543
  await withdrawCallPresence();
3274
3544
  if (dataUnsubscribe) {
3275
3545
  dataUnsubscribe();
@@ -3288,7 +3558,8 @@ function createSession(config) {
3288
3558
  get participants() {
3289
3559
  if (meshManager) {
3290
3560
  return meshManager.getParticipants().map((p) => ({
3291
- agentDid: p.did,
3561
+ participantId: p.did,
3562
+ agentDid: agentOfMeshPeer(p.did),
3292
3563
  stream: p.stream,
3293
3564
  hasAudio: p.hasAudio,
3294
3565
  hasVideo: p.hasVideo,
@@ -3297,6 +3568,7 @@ function createSession(config) {
3297
3568
  }
3298
3569
  if (sfuManager) {
3299
3570
  return sfuManager.getParticipants().map((p) => ({
3571
+ participantId: p.participantId,
3300
3572
  agentDid: p.did,
3301
3573
  stream: p.stream,
3302
3574
  hasAudio: p.hasAudio,
@@ -3381,11 +3653,13 @@ function createSession(config) {
3381
3653
  }
3382
3654
  },
3383
3655
  async destroy() {
3656
+ destroying = true;
3384
3657
  const mesh = meshManager;
3385
3658
  const sfu = sfuManager;
3386
3659
  if (state === "active" || state === "joining")
3387
3660
  await session.leave();
3388
3661
  stopRosterPolling();
3662
+ releaseDevice();
3389
3663
  if (mesh) {
3390
3664
  await mesh.destroy();
3391
3665
  }
@@ -3490,6 +3764,7 @@ var NeighbourhoodProxy = class {
3490
3764
  }
3491
3765
  }
3492
3766
  const proxy = this;
3767
+ const deviceId = options?.deviceId || defaultDeviceId();
3493
3768
  const session = createSession({
3494
3769
  api: __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f"),
3495
3770
  roomId: roomName,
@@ -3498,9 +3773,10 @@ var NeighbourhoodProxy = class {
3498
3773
  topology: options?.topology ?? "auto",
3499
3774
  sfuConfig: options?.sfuConfig,
3500
3775
  iceServers: options?.iceServers,
3776
+ deviceId,
3501
3777
  localSfuStatus: __classPrivateFieldGet$a(this, _NeighbourhoodProxy_sfuStatusCache, "f") ?? void 0,
3502
3778
  sfuServesAllMembers: () => __classPrivateFieldGet$a(proxy, _NeighbourhoodProxy_client, "f").sfuServesAllMembers(__classPrivateFieldGet$a(proxy, _NeighbourhoodProxy_pID, "f")),
3503
- channel: createTelepresenceChannel(proxy, __classPrivateFieldGet$a(proxy, _NeighbourhoodProxy_agentDid, "f")),
3779
+ channel: createTelepresenceChannel(proxy, __classPrivateFieldGet$a(proxy, _NeighbourhoodProxy_agentDid, "f"), deviceId),
3504
3780
  ownOnlineStatus: () => proxy.ownOnlineStatus(),
3505
3781
  setOnlineStatus: (status) => proxy.setOnlineStatusU(status),
3506
3782
  onlineAgents: () => proxy.onlineAgents()
@@ -3536,17 +3812,20 @@ var NeighbourhoodProxy = class {
3536
3812
  async sfuListRooms() {
3537
3813
  return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuListRooms();
3538
3814
  }
3539
- async callJoin(neighbourhoodUrl, roomName, sdpOffer) {
3540
- return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallJoin(neighbourhoodUrl, roomName, sdpOffer);
3815
+ async callJoin(neighbourhoodUrl, roomName, sdpOffer, deviceId, sessionKey) {
3816
+ return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallJoin(neighbourhoodUrl, roomName, sdpOffer, deviceId, sessionKey);
3541
3817
  }
3542
- async callLeave(neighbourhoodUrl, roomName) {
3543
- return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallLeave(neighbourhoodUrl, roomName);
3818
+ async callLeave(neighbourhoodUrl, roomName, participantId) {
3819
+ return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallLeave(neighbourhoodUrl, roomName, participantId);
3544
3820
  }
3545
- async callSetQualityPreference(neighbourhoodUrl, roomName, preference) {
3546
- return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallSetQualityPreference(neighbourhoodUrl, roomName, preference);
3821
+ async callSetQualityPreference(neighbourhoodUrl, roomName, participantId, preference) {
3822
+ return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallSetQualityPreference(neighbourhoodUrl, roomName, participantId, preference);
3547
3823
  }
3548
- async callAnswerServerOffer(neighbourhoodUrl, roomName, sdpAnswer) {
3549
- return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallAnswerServerOffer(neighbourhoodUrl, roomName, sdpAnswer);
3824
+ async callAnswerServerOffer(neighbourhoodUrl, roomName, participantId, sdpAnswer) {
3825
+ return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallAnswerServerOffer(neighbourhoodUrl, roomName, participantId, sdpAnswer);
3826
+ }
3827
+ subscribeSessionReplaced(callback) {
3828
+ return __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").subscribeSfuSessionReplaced(callback);
3550
3829
  }
3551
3830
  subscribeCallRenegotiationOffer(targetDid, callback) {
3552
3831
  return __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").subscribeSfuCallRenegotiationOffer(targetDid, callback);
@@ -3554,11 +3833,11 @@ var NeighbourhoodProxy = class {
3554
3833
  subscribeMigrateEvent(targetDid, callback) {
3555
3834
  return __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").subscribeSfuMigrateEvent(targetDid, callback);
3556
3835
  }
3557
- async addIceCandidate(neighbourhoodUrl, roomName, candidate) {
3558
- return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuAddIceCandidate(neighbourhoodUrl, roomName, candidate);
3836
+ async addIceCandidate(neighbourhoodUrl, roomName, participantId, candidate) {
3837
+ return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuAddIceCandidate(neighbourhoodUrl, roomName, participantId, candidate);
3559
3838
  }
3560
- async sendData(neighbourhoodUrl, roomName, channelLabel, data, binary = false) {
3561
- return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuSendData(neighbourhoodUrl, roomName, channelLabel, data, binary);
3839
+ async sendData(neighbourhoodUrl, roomName, participantId, channelLabel, data, binary = false) {
3840
+ return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuSendData(neighbourhoodUrl, roomName, participantId, channelLabel, data, binary);
3562
3841
  }
3563
3842
  subscribeDataChannel(callback) {
3564
3843
  return __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").subscribeSfuDataChannel(callback);
@@ -6843,15 +7122,25 @@ var __classPrivateFieldGet$6 = function(receiver, state, kind, f) {
6843
7122
  throw new TypeError("Cannot read private member from an object whose class did not declare it");
6844
7123
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6845
7124
  };
7125
+ var _PerspectiveClient_instances;
6846
7126
  var _PerspectiveClient_apiClient;
6847
7127
  var _PerspectiveClient_expressionClient;
6848
7128
  var _PerspectiveClient_neighbourhoodClient;
6849
7129
  var _PerspectiveClient_aiClient;
7130
+ var _PerspectiveClient_released;
6850
7131
  function classParams(className) {
6851
7132
  return Array.isArray(className) ? { class_names: className } : { class_name: className };
6852
7133
  }
7134
+ function mintSubscriptionId() {
7135
+ const b = globalThis.crypto.getRandomValues(new Uint8Array(16));
7136
+ b[6] = b[6] & 15 | 64;
7137
+ b[8] = b[8] & 63 | 128;
7138
+ const hex = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
7139
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
7140
+ }
6853
7141
  var PerspectiveClient = class {
6854
7142
  constructor(baseUrl, token, sharedApiClient) {
7143
+ _PerspectiveClient_instances.add(this);
6855
7144
  _PerspectiveClient_apiClient.set(this, void 0);
6856
7145
  _PerspectiveClient_expressionClient.set(this, void 0);
6857
7146
  _PerspectiveClient_neighbourhoodClient.set(this, void 0);
@@ -6919,7 +7208,8 @@ var PerspectiveClient = class {
6919
7208
  return JSON.parse(result);
6920
7209
  }
6921
7210
  async subscribeQuery(uuid, query, options) {
6922
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call("perspective.subscribeQuery", { uuid, query }, options);
7211
+ const subscriptionId = mintSubscriptionId();
7212
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_released).call(this, uuid, subscriptionId, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call("perspective.subscribeQuery", { uuid, query, subscriptionId }, options));
6923
7213
  }
6924
7214
  onQueryUpdate(cb) {
6925
7215
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").on("query-subscription-update", cb);
@@ -6947,7 +7237,8 @@ var PerspectiveClient = class {
6947
7237
  return JSON.parse(resultJson);
6948
7238
  }
6949
7239
  async modelSubscribe(uuid, className, queryJson, options) {
6950
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call("perspective.modelSubscribe", { uuid, ...classParams(className), query_json: queryJson }, options);
7240
+ const subscriptionId = mintSubscriptionId();
7241
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_released).call(this, uuid, subscriptionId, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call("perspective.modelSubscribe", { uuid, ...classParams(className), query_json: queryJson, subscriptionId }, options));
6951
7242
  }
6952
7243
  async add(name) {
6953
7244
  const handle = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call("perspective.create", { name });
@@ -7122,7 +7413,15 @@ var PerspectiveClient = class {
7122
7413
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").onReconnect(callback);
7123
7414
  }
7124
7415
  };
7125
- _PerspectiveClient_apiClient = /* @__PURE__ */ new WeakMap(), _PerspectiveClient_expressionClient = /* @__PURE__ */ new WeakMap(), _PerspectiveClient_neighbourhoodClient = /* @__PURE__ */ new WeakMap(), _PerspectiveClient_aiClient = /* @__PURE__ */ new WeakMap();
7416
+ _PerspectiveClient_apiClient = /* @__PURE__ */ new WeakMap(), _PerspectiveClient_expressionClient = /* @__PURE__ */ new WeakMap(), _PerspectiveClient_neighbourhoodClient = /* @__PURE__ */ new WeakMap(), _PerspectiveClient_aiClient = /* @__PURE__ */ new WeakMap(), _PerspectiveClient_instances = /* @__PURE__ */ new WeakSet(), _PerspectiveClient_released = async function _PerspectiveClient_released2(uuid, subscriptionId, call) {
7417
+ try {
7418
+ return await call;
7419
+ } catch (e) {
7420
+ this.disposeQuerySubscription(uuid, subscriptionId).catch(() => {
7421
+ });
7422
+ throw e;
7423
+ }
7424
+ };
7126
7425
  var __classPrivateFieldSet$5 = function(receiver, state, value, kind, f) {
7127
7426
  if (kind === "m")
7128
7427
  throw new TypeError("Private method is not writable");