@coasys/ad4m 0.13.1-staging.1 → 0.13.1-staging.2

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 (222) hide show
  1. package/lib/index.cjs +3789 -1192
  2. package/lib/index.js +3783 -1193
  3. package/lib/src/generated/api/AgentsByDidsRequest.d.ts +3 -0
  4. package/lib/src/generated/api/CallSessionInfo.d.ts +23 -0
  5. package/lib/src/generated/api/DiscardBatchRequest.d.ts +3 -0
  6. package/lib/src/generated/api/Events.d.ts +13 -3
  7. package/lib/src/generated/api/Events.js +1 -0
  8. package/lib/src/generated/api/FlowStateChangedEvent.d.ts +38 -0
  9. package/lib/src/generated/api/FlowStateEntry.d.ts +18 -0
  10. package/lib/src/generated/api/FlowStateEntry.js +2 -0
  11. package/lib/src/generated/api/IceServer.d.ts +18 -0
  12. package/lib/src/generated/api/IceServer.js +2 -0
  13. package/lib/src/generated/api/OnlineAgent.d.ts +4 -0
  14. package/lib/src/generated/api/PerspectiveDiscardBatchParams.d.ts +4 -0
  15. package/lib/src/generated/api/PerspectiveDiscardBatchParams.js +2 -0
  16. package/lib/src/generated/api/PerspectiveFlowFiredParams.d.ts +8 -0
  17. package/lib/src/generated/api/PerspectiveFlowFiredParams.js +2 -0
  18. package/lib/src/generated/api/PerspectiveFlowStatesParams.d.ts +11 -0
  19. package/lib/src/generated/api/PerspectiveFlowStatesParams.js +2 -0
  20. package/lib/src/generated/api/PerspectiveGetAllShaclParams.d.ts +7 -0
  21. package/lib/src/generated/api/PerspectiveGetAllShaclParams.js +2 -0
  22. package/lib/src/generated/api/PerspectiveModelQueryParams.d.ts +6 -1
  23. package/lib/src/generated/api/PerspectiveRemoveSubjectParams.d.ts +6 -0
  24. package/lib/src/generated/api/PerspectiveRemoveSubjectParams.js +2 -0
  25. package/lib/src/generated/api/PerspectiveResynced.d.ts +8 -0
  26. package/lib/src/generated/api/PerspectiveResynced.js +2 -0
  27. package/lib/src/generated/api/PerspectiveSubscribed.d.ts +10 -0
  28. package/lib/src/generated/api/PerspectiveSubscribed.js +2 -0
  29. package/lib/src/generated/api/PerspectiveUpdateSubjectParams.d.ts +10 -0
  30. package/lib/src/generated/api/PerspectiveUpdateSubjectParams.js +2 -0
  31. package/lib/src/generated/api/QuerySubscriptionUpdate.d.ts +19 -0
  32. package/lib/src/generated/api/QuerySubscriptionUpdate.js +2 -0
  33. package/lib/src/generated/api/QuerySubscriptionUpdateEvent.d.ts +7 -0
  34. package/lib/src/generated/api/QuerySubscriptionUpdateEvent.js +1 -0
  35. package/lib/src/generated/api/QueryUpdatesLagged.d.ts +7 -0
  36. package/lib/src/generated/api/QueryUpdatesLagged.js +2 -0
  37. package/lib/src/generated/api/RemoveSubjectRequest.d.ts +9 -0
  38. package/lib/src/generated/api/RemoveSubjectRequest.js +2 -0
  39. package/lib/src/generated/api/ResyncSubscriptionRequest.d.ts +3 -0
  40. package/lib/src/generated/api/ResyncSubscriptionRequest.js +2 -0
  41. package/lib/src/generated/api/RpcMethods.d.ts +134 -14
  42. package/lib/src/generated/api/RpcMethods.js +12 -0
  43. package/lib/src/generated/api/SfuAddIceCandidateParams.d.ts +8 -0
  44. package/lib/src/generated/api/SfuAddIceCandidateParams.js +2 -0
  45. package/lib/src/generated/api/SfuAnswerServerOfferParams.d.ts +8 -0
  46. package/lib/src/generated/api/SfuAnswerServerOfferParams.js +2 -0
  47. package/lib/src/generated/api/SfuCallJoinParams.d.ts +14 -0
  48. package/lib/src/generated/api/SfuCallJoinParams.js +2 -0
  49. package/lib/src/generated/api/SfuCallRenegotiationOffer.d.ts +30 -0
  50. package/lib/src/generated/api/SfuCallRenegotiationOffer.js +1 -0
  51. package/lib/src/generated/api/SfuCascadePipe.d.ts +4 -0
  52. package/lib/src/generated/api/SfuCascadePipe.js +2 -0
  53. package/lib/src/generated/api/SfuCascadeStatus.d.ts +8 -0
  54. package/lib/src/generated/api/SfuCascadeStatus.js +1 -0
  55. package/lib/src/generated/api/SfuConfig.d.ts +52 -0
  56. package/lib/src/generated/api/SfuConfig.js +1 -0
  57. package/lib/src/generated/api/SfuDataMessage.d.ts +24 -0
  58. package/lib/src/generated/api/SfuDataMessage.js +2 -0
  59. package/lib/src/generated/api/SfuEnsureMembershipParams.d.ts +4 -0
  60. package/lib/src/generated/api/SfuEnsureMembershipParams.js +2 -0
  61. package/lib/src/generated/api/SfuMigrateEvent.d.ts +21 -0
  62. package/lib/src/generated/api/SfuMigrateEvent.js +2 -0
  63. package/lib/src/generated/api/SfuNeighbourhoodParams.d.ts +3 -0
  64. package/lib/src/generated/api/SfuNeighbourhoodParams.js +2 -0
  65. package/lib/src/generated/api/SfuParticipantQualityPreference.d.ts +7 -0
  66. package/lib/src/generated/api/SfuParticipantQualityPreference.js +2 -0
  67. package/lib/src/generated/api/SfuPerspectiveParams.d.ts +6 -0
  68. package/lib/src/generated/api/SfuPerspectiveParams.js +2 -0
  69. package/lib/src/generated/api/SfuQualityPreferenceParams.d.ts +8 -0
  70. package/lib/src/generated/api/SfuQualityPreferenceParams.js +2 -0
  71. package/lib/src/generated/api/SfuRoomInfo.d.ts +11 -0
  72. package/lib/src/generated/api/SfuRoomInfo.js +1 -0
  73. package/lib/src/generated/api/SfuRoomParams.d.ts +4 -0
  74. package/lib/src/generated/api/SfuRoomParams.js +2 -0
  75. package/lib/src/generated/api/SfuRoomParticipantInfo.d.ts +11 -0
  76. package/lib/src/generated/api/SfuRoomParticipantInfo.js +2 -0
  77. package/lib/src/generated/api/SfuRoomRoster.d.ts +13 -0
  78. package/lib/src/generated/api/SfuRoomRoster.js +2 -0
  79. package/lib/src/generated/api/SfuSendDataParams.d.ts +10 -0
  80. package/lib/src/generated/api/SfuSendDataParams.js +2 -0
  81. package/lib/src/generated/api/SfuSetConfigParams.d.ts +5 -0
  82. package/lib/src/generated/api/SfuSetConfigParams.js +1 -0
  83. package/lib/src/generated/api/SfuStatus.d.ts +24 -0
  84. package/lib/src/generated/api/SfuStatus.js +2 -0
  85. package/lib/src/generated/api/TrackMapEntry.d.ts +17 -0
  86. package/lib/src/generated/api/TrackMapEntry.js +2 -0
  87. package/lib/src/generated/api/UpdateSubjectRequest.d.ts +12 -0
  88. package/lib/src/generated/api/UpdateSubjectRequest.js +2 -0
  89. package/lib/src/generated/api/index.d.ts +3 -0
  90. package/lib/src/index.d.ts +7 -0
  91. package/lib/src/index.js +4 -0
  92. package/lib/src/model/Ad4mModel.d.ts +84 -0
  93. package/lib/src/model/Ad4mModel.js +234 -4
  94. package/lib/src/model/ModelQueryBuilder.d.ts +16 -35
  95. package/lib/src/model/ModelQueryBuilder.js +88 -270
  96. package/lib/src/model/decorators.d.ts +32 -0
  97. package/lib/src/model/decorators.js +40 -1
  98. package/lib/src/model/shacl-gen.d.ts +3 -1
  99. package/lib/src/model/shacl-gen.js +13 -1
  100. package/lib/src/model/types.d.ts +7 -0
  101. package/lib/src/neighbourhood/MeshManager.d.ts +384 -0
  102. package/lib/src/neighbourhood/MeshManager.js +1144 -0
  103. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +91 -0
  104. package/lib/src/neighbourhood/NeighbourhoodClient.js +196 -0
  105. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +55 -1
  106. package/lib/src/neighbourhood/NeighbourhoodProxy.js +170 -3
  107. package/lib/src/neighbourhood/Session.d.ts +105 -0
  108. package/lib/src/neighbourhood/Session.js +412 -0
  109. package/lib/src/neighbourhood/SfuManager.d.ts +174 -0
  110. package/lib/src/neighbourhood/SfuManager.js +619 -0
  111. package/lib/src/neighbourhood/SfuTypes.d.ts +35 -0
  112. package/lib/src/neighbourhood/SfuTypes.js +8 -0
  113. package/lib/src/perspectives/FlowInstance.d.ts +63 -24
  114. package/lib/src/perspectives/FlowInstance.js +74 -31
  115. package/lib/src/perspectives/FlowModels.d.ts +0 -16
  116. package/lib/src/perspectives/FlowModels.js +8 -16
  117. package/lib/src/perspectives/LiveQuery.d.ts +49 -0
  118. package/lib/src/perspectives/LiveQuery.js +169 -0
  119. package/lib/src/perspectives/PerspectiveClient.d.ts +24 -15
  120. package/lib/src/perspectives/PerspectiveClient.js +33 -36
  121. package/lib/src/perspectives/PerspectiveProxy.d.ts +67 -167
  122. package/lib/src/perspectives/PerspectiveProxy.js +121 -475
  123. package/lib/src/perspectives/TextContent.d.ts +31 -0
  124. package/lib/src/perspectives/TextContent.js +52 -0
  125. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +23 -0
  126. package/lib/src/perspectives/WakerSubscriptionManager.js +58 -17
  127. package/lib/src/shacl/SHACLFlow.d.ts +7 -4
  128. package/lib/src/shacl/SHACLFlow.js +7 -4
  129. package/lib/src/shacl/SHACLShape.d.ts +9 -0
  130. package/lib/src/shacl/SHACLShape.js +37 -0
  131. package/package.json +2 -2
  132. package/pnpm-workspace.yaml +4 -1
  133. package/src/Ad4mClient.test.ts +89 -17
  134. package/src/generated/api/AgentsByDidsRequest.ts +3 -0
  135. package/src/generated/api/CallSessionInfo.ts +20 -0
  136. package/src/generated/api/DiscardBatchRequest.ts +3 -0
  137. package/src/generated/api/Events.ts +14 -3
  138. package/src/generated/api/FlowStateChangedEvent.ts +36 -0
  139. package/src/generated/api/FlowStateEntry.ts +18 -0
  140. package/src/generated/api/IceServer.ts +19 -0
  141. package/src/generated/api/OnlineAgent.ts +6 -1
  142. package/src/generated/api/PerspectiveDiscardBatchParams.ts +3 -0
  143. package/src/generated/api/PerspectiveFlowFiredParams.ts +7 -0
  144. package/src/generated/api/PerspectiveFlowStatesParams.ts +11 -0
  145. package/src/generated/api/PerspectiveGetAllShaclParams.ts +6 -0
  146. package/src/generated/api/PerspectiveModelQueryParams.ts +5 -1
  147. package/src/generated/api/PerspectiveRemoveSubjectParams.ts +3 -0
  148. package/src/generated/api/PerspectiveResynced.ts +7 -0
  149. package/src/generated/api/PerspectiveSubscribed.ts +8 -0
  150. package/src/generated/api/PerspectiveUpdateSubjectParams.ts +7 -0
  151. package/src/generated/api/QuerySubscriptionUpdate.ts +10 -0
  152. package/src/generated/api/QuerySubscriptionUpdateEvent.ts +9 -0
  153. package/src/generated/api/QueryUpdatesLagged.ts +7 -0
  154. package/src/generated/api/RemoveSubjectRequest.ts +7 -0
  155. package/src/generated/api/ResyncSubscriptionRequest.ts +3 -0
  156. package/src/generated/api/RpcMethods.ts +68 -8
  157. package/src/generated/api/SfuAddIceCandidateParams.ts +7 -0
  158. package/src/generated/api/SfuAnswerServerOfferParams.ts +7 -0
  159. package/src/generated/api/SfuCallJoinParams.ts +13 -0
  160. package/src/generated/api/SfuCallRenegotiationOffer.ts +29 -0
  161. package/src/generated/api/SfuCascadePipe.ts +3 -0
  162. package/src/generated/api/SfuCascadeStatus.ts +7 -0
  163. package/src/generated/api/SfuConfig.ts +53 -0
  164. package/src/generated/api/SfuDataMessage.ts +23 -0
  165. package/src/generated/api/SfuEnsureMembershipParams.ts +3 -0
  166. package/src/generated/api/SfuMigrateEvent.ts +20 -0
  167. package/src/generated/api/{KeepAliveQueryRequest.ts → SfuNeighbourhoodParams.ts} +1 -1
  168. package/src/generated/api/SfuParticipantQualityPreference.ts +6 -0
  169. package/src/generated/api/{PerspectiveSubscribeQueryResult.ts → SfuPerspectiveParams.ts} +4 -1
  170. package/src/generated/api/SfuQualityPreferenceParams.ts +7 -0
  171. package/src/generated/api/SfuRoomInfo.ts +7 -0
  172. package/src/generated/api/SfuRoomParams.ts +3 -0
  173. package/src/generated/api/SfuRoomParticipantInfo.ts +8 -0
  174. package/src/generated/api/SfuRoomRoster.ts +12 -0
  175. package/src/generated/api/SfuSendDataParams.ts +7 -0
  176. package/src/generated/api/SfuSetConfigParams.ts +4 -0
  177. package/src/generated/api/SfuStatus.ts +24 -0
  178. package/src/generated/api/TrackMapEntry.ts +18 -0
  179. package/src/generated/api/UpdateSubjectRequest.ts +10 -0
  180. package/src/generated/api/index.ts +3 -0
  181. package/src/index.ts +7 -0
  182. package/src/model/Ad4mModel.test.ts +255 -231
  183. package/src/model/Ad4mModel.ts +271 -4
  184. package/src/model/ModelQueryBuilder.ts +103 -310
  185. package/src/model/abstract-classes.test.ts +225 -0
  186. package/src/model/decorators.ts +81 -0
  187. package/src/model/shacl-gen.ts +13 -0
  188. package/src/model/types.ts +7 -0
  189. package/src/neighbourhood/MeshManager.test.ts +2640 -0
  190. package/src/neighbourhood/MeshManager.ts +1350 -0
  191. package/src/neighbourhood/NeighbourhoodClient.ts +271 -0
  192. package/src/neighbourhood/NeighbourhoodProxy.test.ts +23 -0
  193. package/src/neighbourhood/NeighbourhoodProxy.ts +247 -1
  194. package/src/neighbourhood/Session.test.ts +800 -0
  195. package/src/neighbourhood/Session.ts +525 -0
  196. package/src/neighbourhood/SfuManager.test.ts +677 -0
  197. package/src/neighbourhood/SfuManager.ts +803 -0
  198. package/src/neighbourhood/SfuTypes.ts +40 -0
  199. package/src/perspectives/FlowInstance.ts +108 -31
  200. package/src/perspectives/FlowModels.ts +8 -18
  201. package/src/perspectives/LiveQuery.test.ts +197 -0
  202. package/src/perspectives/LiveQuery.ts +189 -0
  203. package/src/perspectives/PerspectiveClient.ts +51 -51
  204. package/src/perspectives/PerspectiveProxy.test.ts +85 -401
  205. package/src/perspectives/PerspectiveProxy.ts +126 -536
  206. package/src/perspectives/TextContent.test.ts +123 -0
  207. package/src/perspectives/TextContent.ts +36 -0
  208. package/src/perspectives/WakerSubscriptionManager.test.ts +88 -6
  209. package/src/perspectives/WakerSubscriptionManager.ts +69 -18
  210. package/src/shacl/SHACLFlow.ts +7 -4
  211. package/src/shacl/SHACLShape.test.ts +2 -1
  212. package/src/shacl/SHACLShape.ts +49 -0
  213. package/lib/src/generated/api/KeepAliveQueryRequest.d.ts +0 -3
  214. package/lib/src/generated/api/PerspectiveModelSubscribeResult.d.ts +0 -7
  215. package/lib/src/generated/api/PerspectiveQuerySubscriptionFilter.d.ts +0 -6
  216. package/lib/src/generated/api/PerspectiveSubscribeQueryResult.d.ts +0 -4
  217. package/src/generated/api/PerspectiveModelSubscribeResult.ts +0 -6
  218. package/src/generated/api/PerspectiveQuerySubscriptionFilter.ts +0 -3
  219. /package/lib/src/generated/api/{KeepAliveQueryRequest.js → AgentsByDidsRequest.js} +0 -0
  220. /package/lib/src/generated/api/{PerspectiveModelSubscribeResult.js → CallSessionInfo.js} +0 -0
  221. /package/lib/src/generated/api/{PerspectiveQuerySubscriptionFilter.js → DiscardBatchRequest.js} +0 -0
  222. /package/lib/src/generated/api/{PerspectiveSubscribeQueryResult.js → FlowStateChangedEvent.js} +0 -0
@@ -0,0 +1,1144 @@
1
+ /**
2
+ * Peer-to-peer WebRTC mesh transport for the AD4M SDK Session interface.
3
+ *
4
+ * Ported from WE Framework's call module (`mesh.ts` and `protocol.ts`), which
5
+ * stays wire-compatible with it: a WE mesh peer and an SDK mesh peer in the
6
+ * same call negotiate with each other.
7
+ *
8
+ * ## Mesh, not SFU
9
+ *
10
+ * Every participant connects to every other, so N participants means N−1
11
+ * connections each and each peer uploads its video N−1 times. That caps at
12
+ * roughly four to six peers before upstream bandwidth becomes the limit. The
13
+ * SFU path (`SfuManager`) handles larger rooms; this path needs no server.
14
+ *
15
+ * ## Membership comes from the roster; this class only negotiates
16
+ *
17
+ * {@link MeshManager.setRoster} receives whoever presence says is in the call.
18
+ * Connections are reconciled against it: appear → connect, disappear → tear
19
+ * down. There is no join or leave message, because a peer that crashes never
20
+ * sends one.
21
+ *
22
+ * ## Perfect negotiation
23
+ *
24
+ * Both peers see each other join at slightly different moments and both fire
25
+ * `negotiationneeded`, so offers collide. Each pair has a **polite** peer and
26
+ * an **impolite** one, decided by comparing DIDs, which needs no agreement
27
+ * round-trip. On collision the impolite peer ignores the incoming offer and
28
+ * the polite peer rolls back its own.
29
+ *
30
+ * ## The signalling channel is not reliable
31
+ *
32
+ * Perfect negotiation assumes a reliable ordered channel. Telepresence is
33
+ * neither: the executor confirms it took a message and nothing confirms a peer
34
+ * received it, sends are dispatched concurrently, and the first broadcast on a
35
+ * freshly joined neighbourhood has been measured at eighteen seconds. Against
36
+ * that, a lost offer deadlocks a pair, a candidate overtaking its description
37
+ * gets discarded, and concurrent handling corrupts the state machine. Four
38
+ * mechanisms fix that:
39
+ *
40
+ * 1. **Per-peer serialisation.** Signalling for one peer runs one message at a
41
+ * time ({@link MeshManager.enqueue}).
42
+ * 2. **Candidate buffering.** Candidates arriving before a remote description
43
+ * wait for one.
44
+ * 3. **A recovery ladder.** ICE restart → resend the description → rebuild the
45
+ * pair, escalating, on a sweep ({@link MeshManager.tick}).
46
+ * 4. **A `reset` message**, so a rebuild is agreed rather than unilateral.
47
+ *
48
+ * ## Which connection a message is about
49
+ *
50
+ * A pair has many connections over its life — a rebuild, a reset, a peer that
51
+ * reloads — and the two sides routinely disagree for a moment about which one
52
+ * is current. Applied to the wrong connection, a description is refused by the
53
+ * browser ("The order of m-lines in subsequent offer doesn't match order from
54
+ * previous offer/answer"). So every connection names itself
55
+ * ({@link PeerSlot.generation}) and every message says which connection sent it
56
+ * and which it is for ({@link CallGenerations}). See {@link MeshManager.placeOf}.
57
+ *
58
+ * ## Who repairs
59
+ *
60
+ * Recovery uses the same tie-break as offers: the impolite peer acts first.
61
+ * The polite peer runs the same ladder on a doubled deadline, which covers the
62
+ * case where the impolite side has no slot for the pair at all.
63
+ *
64
+ * ## Signalling via telepresence
65
+ *
66
+ * SDP and ICE travel through the neighbourhood's telepresence channel
67
+ * (`sendBroadcastU` / `addSignalHandler`). See {@link createTelepresenceChannel}.
68
+ */
69
+ // ── Protocol ────────────────────────────────────────────────────────
70
+ /**
71
+ * Checked on receipt; a mismatch is dropped. New message kinds and the
72
+ * generation fields were added without a bump: an old peer ignores a kind it
73
+ * does not know and never reads the generations, so old and new peers still
74
+ * converge. A bump would make them drop every message from each other.
75
+ */
76
+ export const CALL_PROTOCOL_VERSION = 1;
77
+ /**
78
+ * Narrow an untrusted payload off the transport.
79
+ *
80
+ * Everything arriving here was published by another agent, so it gets
81
+ * shape-checked before use. The sender id comes from the transport rather
82
+ * than the payload — a self-reported `from` would lack authentication.
83
+ */
84
+ export function parseCallMessage(payload) {
85
+ if (typeof payload !== "object" || payload === null)
86
+ return null;
87
+ const msg = payload;
88
+ if (msg.v !== CALL_PROTOCOL_VERSION)
89
+ return null;
90
+ if (typeof msg.call !== "string" || !msg.call)
91
+ return null;
92
+ // A malformed generation is dropped rather than failing the message,
93
+ // which leaves it read as a message from a peer that predates them.
94
+ const envelope = { v: msg.v, call: msg.call };
95
+ if (typeof msg.gen === "string" && msg.gen)
96
+ envelope.gen = msg.gen;
97
+ if (typeof msg.peerGen === "string" && msg.peerGen)
98
+ envelope.peerGen = msg.peerGen;
99
+ if (msg.kind === "description") {
100
+ const description = msg.description;
101
+ if (typeof description !== "object" || description === null)
102
+ return null;
103
+ const { type, sdp } = description;
104
+ if (type !== "offer" && type !== "answer" && type !== "pranswer" && type !== "rollback")
105
+ return null;
106
+ if (sdp !== undefined && typeof sdp !== "string")
107
+ return null;
108
+ const offer = msg.offer;
109
+ return {
110
+ ...envelope,
111
+ kind: "description",
112
+ description: { type, sdp },
113
+ ...(Number.isSafeInteger(offer) ? { offer: offer } : {}),
114
+ };
115
+ }
116
+ if (msg.kind === "ice") {
117
+ const candidate = msg.candidate;
118
+ if (typeof candidate !== "object" || candidate === null)
119
+ return null;
120
+ return { ...envelope, kind: "ice", candidate: candidate };
121
+ }
122
+ if (msg.kind === "reset")
123
+ return { ...envelope, kind: "reset" };
124
+ if (msg.kind === "data") {
125
+ const { label, data, binary } = msg;
126
+ if (typeof label !== "string" || typeof data !== "string")
127
+ return null;
128
+ return { ...envelope, kind: "data", label, data, binary: !!binary };
129
+ }
130
+ return null;
131
+ }
132
+ // ── Signalling channel ──────────────────────────────────────────────
133
+ const RTC_PREDICATE = "ad4m://session/rtc";
134
+ const TARGET_ALL = "*";
135
+ /**
136
+ * Bridge NeighbourhoodProxy telepresence to the SignallingChannel
137
+ * the mesh consumes.
138
+ *
139
+ * ## Why unicast runs emulated over broadcast
140
+ *
141
+ * AD4M exposes real directed send (`sendSignalU`), but it remains
142
+ * broken in current executor builds. This adapter addresses over
143
+ * broadcast: the recipient DID goes in the link's `target` and
144
+ * receivers drop anything not addressed to them. That provides
145
+ * **addressing, not privacy** — every peer still receives the payload.
146
+ */
147
+ export function createTelepresenceChannel(proxy, selfDid) {
148
+ const resultListeners = new Set();
149
+ let subscribed = Promise.resolve();
150
+ const report = (result) => {
151
+ for (const cb of resultListeners) {
152
+ try {
153
+ cb(result);
154
+ }
155
+ catch (e) {
156
+ console.error("mesh: publish result listener error:", e);
157
+ }
158
+ }
159
+ };
160
+ return {
161
+ publish(payload, to) {
162
+ const started = Date.now();
163
+ // Every publish must report, or the mesh counts it outstanding forever
164
+ // and never repairs again — so a synchronous throw becomes a rejection.
165
+ let sent;
166
+ try {
167
+ sent = proxy.sendBroadcastU({
168
+ links: [{
169
+ source: JSON.stringify(payload),
170
+ predicate: RTC_PREDICATE,
171
+ target: to?.agentId ?? TARGET_ALL,
172
+ }],
173
+ });
174
+ }
175
+ catch (err) {
176
+ sent = Promise.reject(err);
177
+ }
178
+ sent.then((ok) => report({ ok: ok !== false, ms: Date.now() - started }), (err) => {
179
+ console.error("mesh: telepresence publish failed:", err);
180
+ report({ ok: false, ms: Date.now() - started });
181
+ });
182
+ },
183
+ onMessage(cb) {
184
+ const handler = (signal) => {
185
+ const link = signal?.data?.links?.[0];
186
+ if (!link?.author)
187
+ return;
188
+ /*
189
+ * The sender is the link's author, so it has to be one: the
190
+ * mesh acts on it (offers, answers, `reset`, rebuilds), and an
191
+ * author is only a claim until a signature backs it. The
192
+ * executor verifies both signatures on receipt and records the
193
+ * result in `proof.valid`. Accept a link only when the signal's
194
+ * signature and the link's own both hold, and both are by the
195
+ * same agent — a valid link relayed inside another agent's
196
+ * signal speaks for its author, not for whoever relayed it.
197
+ */
198
+ if (signal.proof?.valid !== true || link.proof?.valid !== true)
199
+ return;
200
+ if (link.author !== signal.author)
201
+ return;
202
+ const { source, predicate, target } = link.data ?? {};
203
+ if (typeof predicate !== "string" || predicate !== RTC_PREDICATE)
204
+ return;
205
+ // Emulated unicast: drop messages addressed to someone else
206
+ if (target && target !== TARGET_ALL && target !== selfDid)
207
+ return;
208
+ // Drop our own echo
209
+ if (link.author === selfDid)
210
+ return;
211
+ let parsed;
212
+ try {
213
+ parsed = JSON.parse(source);
214
+ }
215
+ catch {
216
+ return;
217
+ }
218
+ cb(link.author, parsed);
219
+ };
220
+ subscribed = proxy.addSignalHandler(handler).catch((err) => {
221
+ console.warn("mesh: signal handler registration failed — inbound traffic will get missed:", err);
222
+ });
223
+ return () => proxy.removeSignalHandler(handler);
224
+ },
225
+ listening: () => subscribed,
226
+ onPublishResult(cb) {
227
+ resultListeners.add(cb);
228
+ return () => resultListeners.delete(cb);
229
+ },
230
+ };
231
+ }
232
+ /** Public STUN, and no TURN. Two servers, because ICE queries them in parallel. */
233
+ export const DEFAULT_ICE_SERVERS = [
234
+ { urls: ["stun:stun.l.google.com:19302", "stun:stun1.l.google.com:19302"] },
235
+ ];
236
+ /**
237
+ * How long a pair may sit unconnected before the impolite side intervenes.
238
+ * Only has to outlast a healthy negotiation: a send still in flight defers
239
+ * repair on its own (see {@link MeshManager.outstanding}).
240
+ */
241
+ export const HANDSHAKE_GRACE_MS = 10000;
242
+ /** How long each rung of the ladder is given before escalating to the next. */
243
+ export const RECOVERY_INTERVAL_MS = 8000;
244
+ /**
245
+ * How long `disconnected` is tolerated before an ICE restart. Shorter than the
246
+ * others: `disconnected` often recovers by itself within a second or two.
247
+ */
248
+ export const DISCONNECT_GRACE_MS = 5000;
249
+ /**
250
+ * How many times a pair is repaired before the mesh stops and lets `failed`
251
+ * stand. A pair that failed a full ladder four times needs TURN or a network,
252
+ * and neither is fixed by a fifth attempt. Reset by a successful connection.
253
+ */
254
+ export const MAX_RECOVERY_ATTEMPTS = 4;
255
+ /** How often the mesh looks at its own connections, when not driven by hand. */
256
+ export const SWEEP_INTERVAL_MS = 2000;
257
+ /**
258
+ * The shortest gap between two repairs, whatever asks for them. A settled send
259
+ * calls `tick` and a repair publishes, so without a floor the two chase each
260
+ * other through every pair in the call. Below {@link SWEEP_INTERVAL_MS} so the
261
+ * ordinary cadence is never throttled.
262
+ */
263
+ export const REPAIR_SPACING_MS = 1500;
264
+ /** Candidates held for a remote description that has not arrived. */
265
+ const MAX_EARLY_CANDIDATES = 64;
266
+ /** How many of a peer's replaced connections are remembered, so a late message from one is refused. */
267
+ const MAX_RETIRED_PER_PEER = 16;
268
+ /** Signalling held from agents the roster has not listed yet. Bounded: it buffers for strangers. */
269
+ const MAX_PENDING_PEERS = 16;
270
+ const MAX_PENDING_PER_PEER = 32;
271
+ /** A name for a new connection. Unique enough among one peer's connections, which is all it is compared with. */
272
+ const newGeneration = () => Math.random().toString(36).slice(2, 10);
273
+ /** Whether a remote track currently carries media. A peer that leaves without
274
+ * saying so leaves its tracks `live` but `muted`. */
275
+ const isLive = (track) => track.readyState !== "ended" && !track.muted;
276
+ export class MeshManager {
277
+ constructor(options) {
278
+ this.sweep = null;
279
+ this.callbacks = new Map();
280
+ this.slots = new Map();
281
+ this.states = new Map();
282
+ this.outbound = new Map();
283
+ /** One stream for all outbound tracks, so a peer receives mic and camera grouped. */
284
+ this.outboundStream = null;
285
+ this.closed = false;
286
+ this.channelUnsubscribe = null;
287
+ this.unwatchPublish = null;
288
+ this.pending = new Map();
289
+ /** The peer connections each peer has replaced. Kept past a slot, so a late message cannot revive one. */
290
+ this.retired = new Map();
291
+ this.dataListeners = new Set();
292
+ /**
293
+ * Sends published and not yet reported on. With an unreliable transport,
294
+ * "the peer never answered" and "the message has not left yet" look the
295
+ * same, and repairing the second piles sends onto a stalled executor. Stays
296
+ * zero on a transport without `onPublishResult`.
297
+ */
298
+ this.outstanding = 0;
299
+ /** When a sweep last repaired something — see {@link REPAIR_SPACING_MS}. */
300
+ this.lastRepairAt = 0;
301
+ /**
302
+ * Repairs of a connected pair's unanswered renegotiation, per peer, kept
303
+ * across rebuilds. A slot's `attempts` resets when its connection connects,
304
+ * which a rebuilt pair does before it renegotiates again — so a peer that
305
+ * never answers a renegotiation would be resent to and rebuilt forever.
306
+ * Cleared only when a renegotiation is answered.
307
+ */
308
+ this.renegotiationRepairs = new Map();
309
+ this.channel = options.channel;
310
+ this.callId = options.callId;
311
+ this.selfId = options.selfId;
312
+ this.configuration = {
313
+ iceServers: options.iceServers?.length ? options.iceServers : DEFAULT_ICE_SERVERS,
314
+ // Gather one candidate set before the handshake asks for it, so the
315
+ // STUN round trip is spent while the user reads the permission prompt.
316
+ iceCandidatePoolSize: 1,
317
+ };
318
+ this.createPeerConnection = options.createPeerConnection
319
+ ?? ((configuration) => new RTCPeerConnection(configuration));
320
+ this.now = options.now ?? (() => Date.now());
321
+ this.sweepMs = options.sweepMs ?? SWEEP_INTERVAL_MS;
322
+ }
323
+ // ── Events ──────────────────────────────────────────────────────
324
+ on(event, callback) {
325
+ if (!this.callbacks.has(event))
326
+ this.callbacks.set(event, []);
327
+ this.callbacks.get(event).push(callback);
328
+ }
329
+ off(event, callback) {
330
+ if (!callback) {
331
+ this.callbacks.delete(event);
332
+ return;
333
+ }
334
+ const cbs = this.callbacks.get(event);
335
+ if (cbs) {
336
+ const idx = cbs.indexOf(callback);
337
+ if (idx !== -1)
338
+ cbs.splice(idx, 1);
339
+ if (cbs.length === 0)
340
+ this.callbacks.delete(event);
341
+ }
342
+ }
343
+ emit(event, ...args) {
344
+ const cbs = this.callbacks.get(event);
345
+ if (cbs)
346
+ for (const cb of cbs) {
347
+ try {
348
+ cb(...args);
349
+ }
350
+ catch (e) {
351
+ console.error(`mesh event handler error (${event}):`, e);
352
+ }
353
+ }
354
+ }
355
+ fail(context, error) {
356
+ this.emit("error", new Error(`${context}: ${error}`));
357
+ }
358
+ participant(peerId, slot) {
359
+ return {
360
+ did: peerId,
361
+ stream: slot.stream,
362
+ hasAudio: slot.stream.getAudioTracks().some(isLive),
363
+ hasVideo: slot.stream.getVideoTracks().some(isLive),
364
+ isActiveSpeaker: false,
365
+ };
366
+ }
367
+ // ── Lifecycle ───────────────────────────────────────────────────
368
+ async join(localStream) {
369
+ this.outboundStream = new MediaStream();
370
+ for (const track of localStream.getAudioTracks()) {
371
+ this.outbound.set("audio", track);
372
+ this.outboundStream.addTrack(track);
373
+ }
374
+ for (const track of localStream.getVideoTracks()) {
375
+ this.outbound.set("video", track);
376
+ this.outboundStream.addTrack(track);
377
+ }
378
+ if (typeof this.channel.onPublishResult === "function") {
379
+ this.unwatchPublish = this.channel.onPublishResult(() => {
380
+ this.outstanding = Math.max(0, this.outstanding - 1);
381
+ // A send whose outcome is known is a reason to look now. Deferred,
382
+ // because a transport may report from inside `publish` and a repair
383
+ // publishes — a direct call would re-enter the sweep mid-repair.
384
+ queueMicrotask(() => this.tick());
385
+ });
386
+ }
387
+ this.channelUnsubscribe = this.channel.onMessage((from, payload) => {
388
+ if (this.closed || from === this.selfId)
389
+ return;
390
+ const message = parseCallMessage(payload);
391
+ if (!message || message.call !== this.callId)
392
+ return;
393
+ // The recipient is carried in the payload too, so a fanout-only
394
+ // transport cannot make a bystander negotiate. Data goes to all.
395
+ const to = payload.to;
396
+ if (typeof to === "string" && to !== TARGET_ALL && to !== this.selfId)
397
+ return;
398
+ // Only peers the roster placed in the call. Without this, anyone on
399
+ // the channel could open a connection by sending an offer.
400
+ const slot = this.slots.get(from);
401
+ if (message.kind === "data") {
402
+ if (slot)
403
+ this.handleData(from, message);
404
+ return;
405
+ }
406
+ if (!slot) {
407
+ this.hold(from, message);
408
+ return;
409
+ }
410
+ this.enqueue(from, slot, message);
411
+ });
412
+ // A session announces itself once `join` returns; peers offer at once.
413
+ await this.channel.listening?.();
414
+ /*
415
+ * Spend the transport's first-send cost on something that does not
416
+ * matter. The first broadcast on a freshly joined neighbourhood has
417
+ * been measured at eighteen seconds and every one after it at tens of
418
+ * milliseconds. Without this, the message paying that cost is the
419
+ * first SDP offer. It parses to nothing on every peer — no `kind`.
420
+ */
421
+ this.publish({ v: CALL_PROTOCOL_VERSION, call: this.callId, warm: true });
422
+ if (this.sweepMs > 0)
423
+ this.sweep = setInterval(() => this.tick(), this.sweepMs);
424
+ }
425
+ async leave() {
426
+ this.closed = true;
427
+ if (this.sweep) {
428
+ clearInterval(this.sweep);
429
+ this.sweep = null;
430
+ }
431
+ this.unwatchPublish?.();
432
+ this.unwatchPublish = null;
433
+ if (this.channelUnsubscribe) {
434
+ this.channelUnsubscribe();
435
+ this.channelUnsubscribe = null;
436
+ }
437
+ this.pending.clear();
438
+ this.renegotiationRepairs.clear();
439
+ for (const peerId of [...this.slots.keys()])
440
+ this.removePeer(peerId);
441
+ this.outbound.clear();
442
+ this.outboundStream = null;
443
+ }
444
+ async destroy() {
445
+ await this.leave();
446
+ this.callbacks.clear();
447
+ this.dataListeners.clear();
448
+ }
449
+ // ── Roster management ───────────────────────────────────────────
450
+ /**
451
+ * Reconcile connections against who presence says belongs in the
452
+ * call. Excludes this agent.
453
+ */
454
+ setRoster(peerIds) {
455
+ if (this.closed)
456
+ return;
457
+ const wanted = new Set(peerIds.filter((id) => id !== this.selfId));
458
+ for (const peerId of [...this.slots.keys()]) {
459
+ if (!wanted.has(peerId))
460
+ this.removePeer(peerId);
461
+ }
462
+ for (const peerId of wanted) {
463
+ if (this.slots.has(peerId))
464
+ continue;
465
+ const slot = this.connect(peerId);
466
+ this.emit("participant-joined", this.participant(peerId, slot));
467
+ this.release(peerId, slot);
468
+ }
469
+ // Anything held for an agent the roster does not list will not get wanted.
470
+ for (const peerId of [...this.pending.keys()]) {
471
+ if (!wanted.has(peerId))
472
+ this.pending.delete(peerId);
473
+ }
474
+ }
475
+ // ── Participants and diagnostics ────────────────────────────────
476
+ getParticipants() {
477
+ return [...this.slots].map(([peerId, slot]) => this.participant(peerId, slot));
478
+ }
479
+ peerStates() {
480
+ return new Map(this.states);
481
+ }
482
+ /**
483
+ * Throw one pair's connection away and negotiate it again, telling the
484
+ * peer to do the same. The manual rung of the ladder: reachable from either
485
+ * side regardless of politeness, and it resets the automatic budget.
486
+ */
487
+ reconnect(peerId) {
488
+ const slot = this.slots.get(peerId);
489
+ if (this.closed || !slot)
490
+ return;
491
+ slot.attempts = 0;
492
+ this.renegotiationRepairs.delete(peerId);
493
+ this.rebuild(peerId, { announce: true, rung: "rebuild" });
494
+ }
495
+ /**
496
+ * How this pair's media reaches the other end — `host` on a LAN, `srflx`
497
+ * through NAT, `relay` through TURN — or `null` when nothing is connected.
498
+ * Separates "this pair needs TURN" from "the handshake never finished".
499
+ */
500
+ async transportOf(peerId) {
501
+ const slot = this.slots.get(peerId);
502
+ if (!slot || typeof slot.pc.getStats !== "function")
503
+ return null;
504
+ try {
505
+ const reports = [];
506
+ (await slot.pc.getStats()).forEach((report) => reports.push(report));
507
+ const winner = reports.find((report) => report.type === "candidate-pair" && report.state === "succeeded");
508
+ const localId = winner?.localCandidateId;
509
+ if (!localId)
510
+ return null;
511
+ const local = reports.find((report) => report.type === "local-candidate" && report.id === localId);
512
+ return local?.candidateType ?? null;
513
+ }
514
+ catch (error) {
515
+ this.fail(`reading transport stats for ${peerId}`, error);
516
+ return null;
517
+ }
518
+ }
519
+ // ── Track replacement ────────────────────────────────────────────
520
+ /**
521
+ * Replace the outbound track of a given kind on every peer connection.
522
+ * Uses `RTCRtpSender.replaceTrack` on the sections declared up front, so
523
+ * muting, unmuting and camera↔screen swaps never renegotiate. Pass `null`
524
+ * to stop sending that kind.
525
+ */
526
+ async replaceTrack(kind, track) {
527
+ const previous = this.outbound.get(kind);
528
+ this.outbound.set(kind, track);
529
+ if (this.outboundStream) {
530
+ if (previous)
531
+ this.outboundStream.removeTrack(previous);
532
+ if (track)
533
+ this.outboundStream.addTrack(track);
534
+ }
535
+ if (this.closed)
536
+ return;
537
+ await Promise.all([...this.slots.entries()].map(async ([peerId, slot]) => {
538
+ try {
539
+ const sender = slot.senders.get(kind);
540
+ if (sender) {
541
+ await sender.replaceTrack(track);
542
+ }
543
+ else if (track) {
544
+ // Only reachable if `addTransceiver` failed. This fires
545
+ // `negotiationneeded`, which perfect negotiation resolves.
546
+ slot.senders.set(kind, slot.pc.addTrack(track, this.outboundStream));
547
+ }
548
+ }
549
+ catch (error) {
550
+ this.fail(`replacing ${kind} track for ${peerId}`, error);
551
+ }
552
+ }));
553
+ }
554
+ // ── Data channel ────────────────────────────────────────────────
555
+ /**
556
+ * Send data to all other participants via the signalling channel.
557
+ * The mesh has no server-side relay — data rides the same
558
+ * telepresence broadcast the SDP/ICE messages use.
559
+ */
560
+ sendData(label, data, binary = false) {
561
+ this.publish({ v: CALL_PROTOCOL_VERSION, call: this.callId, to: TARGET_ALL, kind: "data", label, data, binary });
562
+ }
563
+ subscribeDataChannel(callback) {
564
+ this.dataListeners.add(callback);
565
+ return () => this.dataListeners.delete(callback);
566
+ }
567
+ handleData(from, message) {
568
+ const msg = {
569
+ senderDid: from,
570
+ neighbourhoodUrl: "",
571
+ roomName: this.callId,
572
+ channelLabel: message.label,
573
+ binary: message.binary,
574
+ data: message.data,
575
+ };
576
+ for (const cb of this.dataListeners) {
577
+ try {
578
+ cb(msg);
579
+ }
580
+ catch (e) {
581
+ console.error("mesh: data listener error:", e);
582
+ }
583
+ }
584
+ }
585
+ // ── Sending ─────────────────────────────────────────────────────
586
+ /** Every publish goes through here, so {@link outstanding} counts exactly the reported ones. */
587
+ publish(payload, to) {
588
+ if (this.unwatchPublish)
589
+ this.outstanding += 1;
590
+ this.channel.publish(payload, to);
591
+ }
592
+ /**
593
+ * Addressed twice, on purpose: `to` on the publish lets a transport with
594
+ * native unicast send to one peer, and `to` in the payload makes a
595
+ * fanout-only transport filter on receipt.
596
+ */
597
+ send(to, message) {
598
+ this.publish({ v: CALL_PROTOCOL_VERSION, call: this.callId, to, ...message }, { agentId: to });
599
+ }
600
+ /** Which connections a message from this slot is between. */
601
+ stamp(slot) {
602
+ return slot.remoteGeneration ? { gen: slot.generation, peerGen: slot.remoteGeneration } : { gen: slot.generation };
603
+ }
604
+ sendFrom(peerId, slot, message) {
605
+ this.send(peerId, { ...message, ...this.stamp(slot) });
606
+ }
607
+ /** Send the connection's local description, numbered as {@link CallBody} describes. */
608
+ sendDescription(peerId, slot) {
609
+ const { type, sdp } = slot.pc.localDescription;
610
+ const offer = type === "offer" ? ++slot.offers : slot.remoteOffer;
611
+ slot.lastSent = { kind: "description", description: { type, sdp }, ...(offer !== undefined ? { offer } : {}) };
612
+ this.sendFrom(peerId, slot, slot.lastSent);
613
+ }
614
+ retire(peerId, generation) {
615
+ if (!generation)
616
+ return;
617
+ const list = this.retired.get(peerId) ?? [];
618
+ if (list.includes(generation))
619
+ return;
620
+ list.push(generation);
621
+ if (list.length > MAX_RETIRED_PER_PEER)
622
+ list.shift();
623
+ this.retired.set(peerId, list);
624
+ }
625
+ // ── Peer connection management ──────────────────────────────────
626
+ connect(peerId) {
627
+ const existing = this.slots.get(peerId);
628
+ if (existing)
629
+ return existing;
630
+ const pc = this.createPeerConnection(this.configuration);
631
+ const slot = {
632
+ pc,
633
+ generation: newGeneration(),
634
+ remoteGeneration: null,
635
+ // Comparing DIDs gives each pair exactly one polite side
636
+ // without a round trip.
637
+ polite: this.selfId > peerId,
638
+ makingOffer: false,
639
+ ignoreOffer: false,
640
+ stream: new MediaStream(),
641
+ senders: new Map(),
642
+ work: Promise.resolve(),
643
+ remoteReady: false,
644
+ earlyCandidates: [],
645
+ lastSent: null,
646
+ offers: 0,
647
+ remoteOffer: undefined,
648
+ lastResent: null,
649
+ everConnected: false,
650
+ offeredAt: 0,
651
+ renegotiating: false,
652
+ offerDeferred: false,
653
+ since: this.now(),
654
+ lastAttempt: 0,
655
+ attempts: 0,
656
+ disconnectedAt: 0,
657
+ };
658
+ this.slots.set(peerId, slot);
659
+ const negotiate = async () => {
660
+ /*
661
+ * An answerer's first offer waits until the pair connects. Before
662
+ * that this side cannot know its answer arrived; if it was lost,
663
+ * the peer still has its offer out, reads this offer as glare and
664
+ * negotiates afresh, and both sides take the same DTLS role
665
+ * ("Failed to set SSL role"). Connecting proves the peer applied
666
+ * the answer: DTLS needs the fingerprint it carries. Once
667
+ * connected the roles are fixed, so later offers go at once.
668
+ * Read from the connection: the browser can fire this while the
669
+ * peer's offer is being applied, before any answer exists.
670
+ */
671
+ if (pc.remoteDescription?.type === "offer" && !slot.everConnected) {
672
+ slot.offerDeferred = true;
673
+ return;
674
+ }
675
+ slot.offerDeferred = false;
676
+ try {
677
+ slot.makingOffer = true;
678
+ /*
679
+ * Always an offer, never "whatever the state calls for". The
680
+ * browser can fire this during the rollback that accepting the
681
+ * peer's offer starts; a description picked from the state when
682
+ * the call runs is then the answer, and the answering path
683
+ * makes an offer in its place. If the peer's offer got here
684
+ * first the browser refuses, and asks again once stable.
685
+ */
686
+ await pc.setLocalDescription({ type: "offer" });
687
+ slot.offeredAt = this.now();
688
+ slot.renegotiating = pc.connectionState === "connected";
689
+ this.sendDescription(peerId, slot);
690
+ }
691
+ catch (error) {
692
+ if (pc.signalingState === "stable")
693
+ this.fail(`negotiating with ${peerId}`, error);
694
+ }
695
+ finally {
696
+ slot.makingOffer = false;
697
+ }
698
+ };
699
+ pc.onnegotiationneeded = negotiate;
700
+ pc.onicecandidate = ({ candidate }) => {
701
+ if (candidate)
702
+ this.sendFrom(peerId, slot, { kind: "ice", candidate: candidate.toJSON() });
703
+ };
704
+ pc.ontrack = ({ track }) => {
705
+ slot.stream.addTrack(track);
706
+ // Track events outlive the connection; a replaced one reports nothing.
707
+ const current = () => this.slots.get(peerId) === slot;
708
+ const updated = () => {
709
+ if (current())
710
+ this.emit("participant-updated", this.participant(peerId, slot));
711
+ };
712
+ // A replaced track (camera → screen) arrives as a new track and
713
+ // the old one ends. Without this the tile would keep rendering it.
714
+ track.addEventListener("ended", () => {
715
+ slot.stream.removeTrack(track);
716
+ if (!current())
717
+ return;
718
+ this.emit("stream-removed", slot.stream, track);
719
+ updated();
720
+ });
721
+ /*
722
+ * A remote track that stops receiving goes MUTED, not ended. When a
723
+ * peer leaves, crashes or drops off the network the track stays
724
+ * `live` for as long as the connection exists, and a `<video>`
725
+ * goes on painting the last decoded frame. Both edges, because a
726
+ * connection that recovers unmutes the same track.
727
+ */
728
+ track.addEventListener("mute", updated);
729
+ track.addEventListener("unmute", updated);
730
+ this.emit("stream-added", slot.stream, track);
731
+ };
732
+ pc.onconnectionstatechange = () => {
733
+ const state = pc.connectionState;
734
+ this.states.set(peerId, state);
735
+ if (state === "connected") {
736
+ slot.everConnected = true;
737
+ // The budget bounds one failure, not a session: a call that
738
+ // drops and recovers twice must not run out of repairs.
739
+ slot.attempts = 0;
740
+ slot.disconnectedAt = 0;
741
+ // Keep only candidates from a peer connection this one has not met.
742
+ slot.earlyCandidates = slot.earlyCandidates.filter((held) => held.gen && held.gen !== slot.remoteGeneration);
743
+ if (slot.offerDeferred && pc.signalingState === "stable")
744
+ void negotiate();
745
+ }
746
+ if (state === "disconnected" && !slot.disconnectedAt)
747
+ slot.disconnectedAt = this.now();
748
+ if (state === "connected" || state === "failed")
749
+ slot.disconnectedAt = 0;
750
+ this.emit("peer-state", peerId, state);
751
+ // `failed` is actionable at once — there is nothing in flight to wait for.
752
+ if (state === "failed")
753
+ this.tick();
754
+ };
755
+ /*
756
+ * Both m-lines, before there is anything to put in them.
757
+ *
758
+ * A connection can only carry media of a kind it negotiated a section
759
+ * for, and `addTrack` creates one. An agent sending no video negotiated
760
+ * no video section, which left the *other* peer's camera with nowhere
761
+ * to arrive. Declaring both up front makes every track change a
762
+ * `replaceTrack` on an existing section.
763
+ */
764
+ for (const kind of ["audio", "video"]) {
765
+ try {
766
+ slot.senders.set(kind, pc.addTransceiver(kind, {
767
+ direction: "sendrecv",
768
+ streams: this.outboundStream ? [this.outboundStream] : [],
769
+ }).sender);
770
+ }
771
+ catch (error) {
772
+ this.fail(`preparing ${kind} for ${peerId}`, error);
773
+ }
774
+ }
775
+ // Attach whatever already gets sent, so a peer joining mid-call
776
+ // receives our media without waiting for a toggle.
777
+ for (const [kind, track] of this.outbound) {
778
+ if (!track)
779
+ continue;
780
+ const sender = slot.senders.get(kind);
781
+ if (!sender)
782
+ continue;
783
+ void sender.replaceTrack(track).catch((error) => this.fail(`sending ${kind} to ${peerId}`, error));
784
+ }
785
+ return slot;
786
+ }
787
+ /** Close one pair's connection, without telling anyone it happened. */
788
+ disconnect(peerId) {
789
+ const slot = this.slots.get(peerId);
790
+ if (!slot)
791
+ return;
792
+ slot.pc.onnegotiationneeded = null;
793
+ slot.pc.onicecandidate = null;
794
+ slot.pc.ontrack = null;
795
+ slot.pc.onconnectionstatechange = null;
796
+ try {
797
+ slot.pc.close();
798
+ }
799
+ catch (error) {
800
+ this.fail(`closing connection to ${peerId}`, error);
801
+ }
802
+ this.slots.delete(peerId);
803
+ this.states.delete(peerId);
804
+ // A late message from the peer's connection must not be mistaken for a
805
+ // new one when the peer returns.
806
+ this.retire(peerId, slot.remoteGeneration);
807
+ // Held signalling belongs to the connection going away.
808
+ this.pending.delete(peerId);
809
+ }
810
+ /** The peer left the call. */
811
+ removePeer(peerId) {
812
+ const slot = this.slots.get(peerId);
813
+ if (!slot)
814
+ return;
815
+ this.disconnect(peerId);
816
+ this.renegotiationRepairs.delete(peerId);
817
+ this.emit("participant-left", this.participant(peerId, slot));
818
+ }
819
+ // ── Pending message buffer ──────────────────────────────────────
820
+ /**
821
+ * Signalling that arrived before the roster caught up, kept until it does.
822
+ *
823
+ * A peer who denied the microphone has no outbound tracks, so it never
824
+ * fires `negotiationneeded` again after its offer is dropped. It joined and
825
+ * connected to nobody. Bounded on both axes, because this buffers messages
826
+ * from agents the roster has not vouched for. Overflow drops the oldest.
827
+ */
828
+ hold(peerId, message) {
829
+ if (!this.pending.has(peerId) && this.pending.size >= MAX_PENDING_PEERS)
830
+ return;
831
+ const queue = this.pending.get(peerId) ?? [];
832
+ queue.push(message);
833
+ // An offer is followed by its candidates; dropping the oldest message
834
+ // would drop the offer, which the pair cannot start without. Drop the
835
+ // oldest message that is not a description or a reset instead.
836
+ while (queue.length > MAX_PENDING_PER_PEER) {
837
+ const spare = queue.findIndex((held) => held.kind !== "description" && held.kind !== "reset");
838
+ queue.splice(spare === -1 ? 0 : spare, 1);
839
+ }
840
+ this.pending.set(peerId, queue);
841
+ }
842
+ /** Replay what this peer sent while we were still learning it belongs here. */
843
+ release(peerId, slot) {
844
+ const queue = this.pending.get(peerId);
845
+ if (!queue)
846
+ return;
847
+ this.pending.delete(peerId);
848
+ // Enqueued rather than started all at once, on a connection that is
849
+ // also about to fire `negotiationneeded` for its new transceivers.
850
+ for (const message of queue)
851
+ this.enqueue(peerId, slot, message);
852
+ }
853
+ // ── Message handling ────────────────────────────────────────────
854
+ /** Put one message on this peer's queue. The chain never rejects — `handle` reports its own failures. */
855
+ enqueue(peerId, slot, message) {
856
+ slot.work = slot.work.then(async () => {
857
+ if (this.closed)
858
+ return;
859
+ const current = this.slots.get(peerId);
860
+ if (!current)
861
+ return;
862
+ // The pair was rebuilt while this waited. A message that names its
863
+ // connections follows the pair to its replacement and gets judged
864
+ // there; one that does not is about a connection that is gone.
865
+ if (current !== slot) {
866
+ if (message.gen)
867
+ this.enqueue(peerId, current, message);
868
+ return;
869
+ }
870
+ await this.handle(peerId, slot, message);
871
+ });
872
+ }
873
+ /**
874
+ * Where a message stands against the connection this side holds for its sender.
875
+ *
876
+ * - `current` — from the peer connection this one talks to, or the first to
877
+ * name itself, or it names nothing (a peer predating generations).
878
+ * - `stale` — for a connection of this side's that was replaced, or from
879
+ * one of the peer's that was. Nothing it says applies.
880
+ * - `newer` — from a peer connection this side has not met: the peer has started over.
881
+ */
882
+ placeOf(peerId, slot, message) {
883
+ if (message.peerGen && message.peerGen !== slot.generation)
884
+ return "stale";
885
+ if (!message.gen)
886
+ return "current";
887
+ if (this.retired.get(peerId)?.includes(message.gen))
888
+ return "stale";
889
+ if (!slot.remoteGeneration || slot.remoteGeneration === message.gen)
890
+ return "current";
891
+ return "newer";
892
+ }
893
+ async handle(peerId, slot, message) {
894
+ try {
895
+ const place = this.placeOf(peerId, slot, message);
896
+ if (place === "stale")
897
+ return;
898
+ if (place === "current" && message.gen && !slot.remoteGeneration)
899
+ slot.remoteGeneration = message.gen;
900
+ if (message.kind === "reset") {
901
+ // The peer is starting over. Rebuild to match and say nothing
902
+ // back — two peers answering resets with resets is a loop.
903
+ this.retire(peerId, message.gen);
904
+ this.rebuild(peerId, { announce: false, rung: "rebuild" });
905
+ return;
906
+ }
907
+ if (place === "newer") {
908
+ // A candidate can overtake the offer it belongs to, so it waits.
909
+ if (message.kind === "ice") {
910
+ if (slot.earlyCandidates.length < MAX_EARLY_CANDIDATES) {
911
+ slot.earlyCandidates.push({ gen: message.gen, candidate: message.candidate });
912
+ }
913
+ return;
914
+ }
915
+ /*
916
+ * The peer has a connection this side never heard from: a
917
+ * reload, a rebuild whose reset was lost, a reset this offer
918
+ * overtook. Applying its offer here is the "order of m-lines"
919
+ * refusal, so this side starts over too, and applies the offer
920
+ * at once — an offer of its own would collide with it. An
921
+ * answer from an unknown connection has nothing to apply to;
922
+ * the rebuilt side offers afresh.
923
+ */
924
+ const next = this.rebuild(peerId, { announce: false, rung: "rebuild" });
925
+ next.earlyCandidates = slot.earlyCandidates.filter((held) => held.gen === message.gen);
926
+ if (message.kind === "description" && message.description.type === "offer") {
927
+ next.remoteGeneration = message.gen ?? null;
928
+ next.work = this.handle(peerId, next, message);
929
+ }
930
+ return;
931
+ }
932
+ if (message.kind === "description") {
933
+ const { description } = message;
934
+ // An offer older than one already applied — overtaken on this
935
+ // unordered transport — describes m-lines the connection has
936
+ // moved past. The same number again is the resend rung's copy,
937
+ // and is answered.
938
+ if (description.type === "offer" &&
939
+ message.offer !== undefined &&
940
+ slot.remoteOffer !== undefined &&
941
+ message.offer < slot.remoteOffer)
942
+ return;
943
+ const collision = description.type === "offer" &&
944
+ (slot.makingOffer || slot.pc.signalingState !== "stable");
945
+ // The impolite peer wins a collision by ignoring the other's
946
+ // offer; the polite peer yields, and `setRemoteDescription`
947
+ // performs the implicit rollback that lets it accept.
948
+ slot.ignoreOffer = !slot.polite && collision;
949
+ if (slot.ignoreOffer)
950
+ return;
951
+ // An answer with no offer out is a late duplicate — the
952
+ // resend rung got one answer for each copy. Expected on this
953
+ // transport, so not an error.
954
+ if (description.type === "answer" && slot.pc.signalingState === "stable")
955
+ return;
956
+ // An answer to an earlier offer of this connection — a late copy
957
+ // from the resend rung — would be refused against the current one.
958
+ if (description.type === "answer" && message.offer !== undefined && message.offer !== slot.offers)
959
+ return;
960
+ await slot.pc.setRemoteDescription(description);
961
+ if (description.type === "offer")
962
+ slot.remoteOffer = message.offer;
963
+ // An answer settles this side's offer, and accepting the
964
+ // peer's offer rolled it back. Either way none is pending.
965
+ // An answered renegotiation is the evidence the connected-pair
966
+ // repair waits for, so only that clears its budget.
967
+ if (description.type === "answer" && slot.renegotiating) {
968
+ this.renegotiationRepairs.delete(peerId);
969
+ if (slot.pc.connectionState === "connected")
970
+ slot.attempts = 0;
971
+ }
972
+ slot.offeredAt = 0;
973
+ slot.renegotiating = false;
974
+ // Candidates become applicable exactly here. On an unordered
975
+ // transport a candidate overtaking its offer is the normal case.
976
+ slot.remoteReady = true;
977
+ await this.flushCandidates(peerId, slot);
978
+ if (description.type === "offer") {
979
+ await slot.pc.setLocalDescription({ type: "answer" });
980
+ this.sendDescription(peerId, slot);
981
+ }
982
+ return;
983
+ }
984
+ if (message.kind !== "ice")
985
+ return;
986
+ if (!slot.remoteReady) {
987
+ if (slot.earlyCandidates.length < MAX_EARLY_CANDIDATES) {
988
+ slot.earlyCandidates.push({ gen: message.gen, candidate: message.candidate });
989
+ }
990
+ return;
991
+ }
992
+ try {
993
+ await slot.pc.addIceCandidate(message.candidate);
994
+ }
995
+ catch (error) {
996
+ // Candidates for an offer we deliberately ignored will fail,
997
+ // and that is expected. Anything else is real.
998
+ if (!slot.ignoreOffer)
999
+ throw error;
1000
+ }
1001
+ }
1002
+ catch (error) {
1003
+ this.fail(`handling ${message.kind} from ${peerId}`, error);
1004
+ }
1005
+ }
1006
+ async flushCandidates(peerId, slot) {
1007
+ if (!slot.earlyCandidates.length)
1008
+ return;
1009
+ // Only this connection's. A candidate from a peer connection it has not met stays held.
1010
+ const mine = (held) => !held.gen || held.gen === slot.remoteGeneration;
1011
+ const ready = slot.earlyCandidates.filter(mine).map((held) => held.candidate);
1012
+ slot.earlyCandidates = slot.earlyCandidates.filter((held) => !mine(held));
1013
+ for (const candidate of ready) {
1014
+ try {
1015
+ await slot.pc.addIceCandidate(candidate);
1016
+ }
1017
+ catch (error) {
1018
+ // One stale candidate must not stop the rest.
1019
+ this.fail(`applying a held candidate from ${peerId}`, error);
1020
+ }
1021
+ }
1022
+ }
1023
+ // ── Recovery ────────────────────────────────────────────────────
1024
+ /**
1025
+ * Throw this pair away and start again. Attempts carry over to the new
1026
+ * slot, or a pair that rebuilds every time would never reach
1027
+ * {@link MAX_RECOVERY_ATTEMPTS}.
1028
+ */
1029
+ rebuild(peerId, opts) {
1030
+ const previous = this.slots.get(peerId);
1031
+ const attempts = (previous?.attempts ?? 0) + 1;
1032
+ // Sent from the connection being thrown away, so the peer can tell a late reset from a new one.
1033
+ const farewell = previous ? this.stamp(previous) : {};
1034
+ this.disconnect(peerId);
1035
+ if (opts.announce)
1036
+ this.send(peerId, { kind: "reset", ...farewell });
1037
+ const slot = this.connect(peerId);
1038
+ slot.attempts = attempts;
1039
+ slot.lastAttempt = this.now();
1040
+ // The participant's stream is a new object; consumers holding the old one render a dead stream.
1041
+ this.emit("participant-updated", this.participant(peerId, slot));
1042
+ this.emit("peer-recovery", peerId, { rung: opts.rung, attempts });
1043
+ return slot;
1044
+ }
1045
+ /**
1046
+ * One pair, one repair, on whichever rung its state calls for, cheapest first:
1047
+ *
1048
+ * 1. **ICE restart.** Keeps the connection and DTLS session; only
1049
+ * re-gathers the transport. For `failed` and a `disconnected` that did
1050
+ * not come back.
1051
+ * 2. **Resend the description.** For a handshake that never completed,
1052
+ * which on this transport means a message was dropped — either half.
1053
+ * 3. **Rebuild.** When there is nothing to resend, or the rungs above were tried.
1054
+ */
1055
+ repair(peerId, slot) {
1056
+ slot.lastAttempt = this.now();
1057
+ const attempts = slot.attempts + 1;
1058
+ slot.attempts = attempts;
1059
+ const state = slot.pc.connectionState;
1060
+ const canRestart = typeof slot.pc.restartIce === "function";
1061
+ if ((state === "failed" || state === "disconnected") && canRestart && slot.remoteReady) {
1062
+ try {
1063
+ slot.pc.restartIce();
1064
+ this.emit("peer-recovery", peerId, { rung: "ice-restart", attempts });
1065
+ return;
1066
+ }
1067
+ catch (error) {
1068
+ this.fail(`restarting ice with ${peerId}`, error);
1069
+ }
1070
+ }
1071
+ const unanswered = slot.offeredAt > 0 && slot.pc.signalingState === "have-local-offer";
1072
+ if (state === "connected") {
1073
+ this.renegotiationRepairs.set(peerId, (this.renegotiationRepairs.get(peerId) ?? 0) + 1);
1074
+ }
1075
+ if ((!slot.everConnected || unanswered) && slot.lastSent && slot.lastSent.description.sdp !== slot.lastResent) {
1076
+ slot.lastResent = slot.lastSent.description.sdp ?? null;
1077
+ this.sendFrom(peerId, slot, slot.lastSent);
1078
+ this.emit("peer-recovery", peerId, { rung: "resend", attempts });
1079
+ return;
1080
+ }
1081
+ // Undo the increment `rebuild` is about to make again, so one repair counts once.
1082
+ slot.attempts = attempts - 1;
1083
+ this.rebuild(peerId, { announce: true, rung: "rebuild" });
1084
+ }
1085
+ /** Whether this pair has been given long enough, and whether it is this side's turn to act. */
1086
+ dueForRepair(peerId, slot, at) {
1087
+ const state = slot.pc.connectionState;
1088
+ if (slot.attempts >= MAX_RECOVERY_ATTEMPTS)
1089
+ return false;
1090
+ /*
1091
+ * Connected, with an offer of this side's never answered. A pair
1092
+ * renegotiates after it connects — the answerer's media travels in
1093
+ * its own offer — and on a reordering transport that offer can reach
1094
+ * an impolite peer before the answer it follows, which reads it as
1095
+ * glare and ignores it. Nothing else revisits a connected pair, so
1096
+ * the media in that direction would never arrive. Only this side can
1097
+ * see the offer is pending, so it acts without the polite wait.
1098
+ */
1099
+ if (state === "connected") {
1100
+ if (!slot.offeredAt || slot.pc.signalingState !== "have-local-offer")
1101
+ return false;
1102
+ if ((this.renegotiationRepairs.get(peerId) ?? 0) >= MAX_RECOVERY_ATTEMPTS)
1103
+ return false;
1104
+ return at - Math.max(slot.offeredAt, slot.lastAttempt) >= RECOVERY_INTERVAL_MS;
1105
+ }
1106
+ // The impolite peer repairs first; the polite one waits twice as long,
1107
+ // which covers an impolite side whose roster never listed this peer.
1108
+ const patience = slot.polite ? 2 : 1;
1109
+ if (state === "disconnected" && slot.disconnectedAt) {
1110
+ return at - slot.disconnectedAt >= DISCONNECT_GRACE_MS * patience;
1111
+ }
1112
+ if (state === "failed") {
1113
+ return at - Math.max(slot.lastAttempt, slot.since) >= RECOVERY_INTERVAL_MS * patience;
1114
+ }
1115
+ // 'new' | 'connecting' | 'closed' — a handshake that has not finished.
1116
+ const from = slot.lastAttempt || slot.since;
1117
+ const deadline = slot.lastAttempt ? RECOVERY_INTERVAL_MS : HANDSHAKE_GRACE_MS;
1118
+ return at - from >= deadline * patience;
1119
+ }
1120
+ /**
1121
+ * Look at every connection and repair what is stuck. Driven by an internal
1122
+ * timer; public because tests drive it by hand.
1123
+ */
1124
+ tick() {
1125
+ if (this.closed)
1126
+ return;
1127
+ // Nothing is repaired while a send is unaccounted for: an offer not
1128
+ // yet delivered and an offer lost look the same from here.
1129
+ if (this.outstanding > 0)
1130
+ return;
1131
+ const at = this.now();
1132
+ if (this.lastRepairAt && at - this.lastRepairAt < REPAIR_SPACING_MS)
1133
+ return;
1134
+ for (const [peerId, slot] of [...this.slots]) {
1135
+ if (!this.dueForRepair(peerId, slot, at))
1136
+ continue;
1137
+ this.lastRepairAt = at;
1138
+ this.repair(peerId, slot);
1139
+ // One pair per sweep: a network that just came back has every pair
1140
+ // due at once, and a burst of offers is what made them fail.
1141
+ break;
1142
+ }
1143
+ }
1144
+ }