@coasys/ad4m 0.13.1-staging.11 → 0.13.1-staging.13

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 (157) hide show
  1. package/lib/index.cjs +547 -72
  2. package/lib/index.js +547 -72
  3. package/lib/src/apiClient.d.ts +7 -2
  4. package/lib/src/apiClient.js +3 -2
  5. package/lib/src/generated/api/AISessionMessage.d.ts +4 -3
  6. package/lib/src/generated/api/AiEndpoint.d.ts +3 -2
  7. package/lib/src/generated/api/Cardinality.d.ts +7 -0
  8. package/lib/src/generated/api/Cardinality.js +2 -0
  9. package/lib/src/generated/api/CascadeStep.d.ts +12 -0
  10. package/lib/src/generated/api/CascadeStep.js +2 -0
  11. package/lib/src/generated/api/CollectionItemAdded.d.ts +14 -0
  12. package/lib/src/generated/api/CollectionItemAdded.js +2 -0
  13. package/lib/src/generated/api/CollectionItemRemoved.d.ts +12 -0
  14. package/lib/src/generated/api/CollectionItemRemoved.js +2 -0
  15. package/lib/src/generated/api/CollectionItems.d.ts +7 -0
  16. package/lib/src/generated/api/CollectionItems.js +2 -0
  17. package/lib/src/generated/api/ConfigChanged.d.ts +8 -0
  18. package/lib/src/generated/api/ConfigChanged.js +2 -0
  19. package/lib/src/generated/api/ConfigKeyInfo.d.ts +10 -0
  20. package/lib/src/generated/api/ConfigKeyInfo.js +1 -0
  21. package/lib/src/generated/api/ConfigRefusal.d.ts +6 -0
  22. package/lib/src/generated/api/ConfigRefusal.js +1 -0
  23. package/lib/src/generated/api/DeviceKeys.d.ts +9 -0
  24. package/lib/src/generated/api/DeviceKeys.js +2 -0
  25. package/lib/src/generated/api/Events.d.ts +2 -0
  26. package/lib/src/generated/api/InstanceAddToCollection.d.ts +16 -0
  27. package/lib/src/generated/api/InstanceAddToCollection.js +2 -0
  28. package/lib/src/generated/api/InstanceCreate.d.ts +31 -0
  29. package/lib/src/generated/api/InstanceCreate.js +2 -0
  30. package/lib/src/generated/api/InstanceCreated.d.ts +17 -0
  31. package/lib/src/generated/api/InstanceCreated.js +1 -0
  32. package/lib/src/generated/api/InstanceError.d.ts +55 -0
  33. package/lib/src/generated/api/InstanceError.js +1 -0
  34. package/lib/src/generated/api/InstanceRemove.d.ts +12 -0
  35. package/lib/src/generated/api/InstanceRemove.js +2 -0
  36. package/lib/src/generated/api/InstanceRemoveFromCollection.d.ts +16 -0
  37. package/lib/src/generated/api/InstanceRemoveFromCollection.js +2 -0
  38. package/lib/src/generated/api/InstanceRemoved.d.ts +10 -0
  39. package/lib/src/generated/api/InstanceRemoved.js +2 -0
  40. package/lib/src/generated/api/InstanceUpdate.d.ts +15 -0
  41. package/lib/src/generated/api/InstanceUpdate.js +2 -0
  42. package/lib/src/generated/api/InstanceUpdated.d.ts +5 -0
  43. package/lib/src/generated/api/InstanceUpdated.js +2 -0
  44. package/lib/src/generated/api/KeyClass.d.ts +4 -0
  45. package/lib/src/generated/api/KeyClass.js +2 -0
  46. package/lib/src/generated/api/LogTail.d.ts +6 -0
  47. package/lib/src/generated/api/LogTail.js +2 -0
  48. package/lib/src/generated/api/LogTailParams.d.ts +9 -0
  49. package/lib/src/generated/api/LogTailParams.js +2 -0
  50. package/lib/src/generated/api/PerspectiveInstanceAddToCollectionParams.d.ts +14 -0
  51. package/lib/src/generated/api/PerspectiveInstanceAddToCollectionParams.js +2 -0
  52. package/lib/src/generated/api/PerspectiveInstanceCreateParams.d.ts +29 -0
  53. package/lib/src/generated/api/PerspectiveInstanceCreateParams.js +2 -0
  54. package/lib/src/generated/api/PerspectiveInstanceRemoveFromCollectionParams.d.ts +14 -0
  55. package/lib/src/generated/api/PerspectiveInstanceRemoveFromCollectionParams.js +2 -0
  56. package/lib/src/generated/api/PerspectiveInstanceRemoveParams.d.ts +9 -0
  57. package/lib/src/generated/api/PerspectiveInstanceRemoveParams.js +2 -0
  58. package/lib/src/generated/api/PerspectiveInstanceUpdateParams.d.ts +13 -0
  59. package/lib/src/generated/api/PerspectiveInstanceUpdateParams.js +2 -0
  60. package/lib/src/generated/api/Pinned.d.ts +5 -0
  61. package/lib/src/generated/api/Pinned.js +2 -0
  62. package/lib/src/generated/api/ReadOnlyReason.d.ts +4 -0
  63. package/lib/src/generated/api/ReadOnlyReason.js +2 -0
  64. package/lib/src/generated/api/RefusalReason.d.ts +4 -0
  65. package/lib/src/generated/api/RefusalReason.js +2 -0
  66. package/lib/src/generated/api/RpcMethods.d.ts +60 -0
  67. package/lib/src/generated/api/RpcMethods.js +3 -0
  68. package/lib/src/generated/api/RuntimeConfig.d.ts +23 -0
  69. package/lib/src/generated/api/RuntimeConfig.js +1 -0
  70. package/lib/src/generated/api/SetConfigParams.d.ts +7 -0
  71. package/lib/src/generated/api/SetConfigParams.js +2 -0
  72. package/lib/src/generated/api/SetConfigResult.d.ts +8 -0
  73. package/lib/src/generated/api/SetConfigResult.js +1 -0
  74. package/lib/src/generated/api/ValidationError.d.ts +34 -0
  75. package/lib/src/generated/api/ValidationError.js +1 -0
  76. package/lib/src/generated/api/ValidationProblem.d.ts +34 -0
  77. package/lib/src/generated/api/ValidationProblem.js +1 -0
  78. package/lib/src/generated/api/WriteStep.d.ts +37 -0
  79. package/lib/src/generated/api/WriteStep.js +2 -0
  80. package/lib/src/generated/api/index.d.ts +30 -0
  81. package/lib/src/identity/IdentityClient.d.ts +14 -0
  82. package/lib/src/identity/IdentityClient.js +17 -0
  83. package/lib/src/model/shacl-gen.js +4 -2
  84. package/lib/src/neighbourhood/MeshManager.d.ts +17 -1
  85. package/lib/src/neighbourhood/MeshManager.js +17 -0
  86. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +7 -2
  87. package/lib/src/neighbourhood/NeighbourhoodProxy.js +7 -2
  88. package/lib/src/neighbourhood/Session.d.ts +5 -3
  89. package/lib/src/neighbourhood/Session.js +171 -26
  90. package/lib/src/perspectives/PerspectiveClient.d.ts +34 -0
  91. package/lib/src/perspectives/PerspectiveClient.js +45 -0
  92. package/lib/src/perspectives/PerspectiveProxy.d.ts +33 -0
  93. package/lib/src/perspectives/PerspectiveProxy.js +67 -2
  94. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +23 -1
  95. package/lib/src/perspectives/WakerSubscriptionManager.js +187 -36
  96. package/lib/src/runtime/RuntimeClient.d.ts +13 -1
  97. package/lib/src/runtime/RuntimeClient.js +20 -0
  98. package/lib/src/shacl/SHACLShape.js +6 -2
  99. package/package.json +2 -2
  100. package/src/Ad4mClient.test.ts +118 -2
  101. package/src/apiClient.ts +10 -4
  102. package/src/generated/api/AISessionMessage.ts +4 -3
  103. package/src/generated/api/AiEndpoint.ts +3 -2
  104. package/src/generated/api/Cardinality.ts +6 -0
  105. package/src/generated/api/CascadeStep.ts +6 -0
  106. package/src/generated/api/CollectionItemAdded.ts +11 -0
  107. package/src/generated/api/CollectionItemRemoved.ts +9 -0
  108. package/src/generated/api/CollectionItems.ts +6 -0
  109. package/src/generated/api/ConfigChanged.ts +7 -0
  110. package/src/generated/api/ConfigKeyInfo.ts +8 -0
  111. package/src/generated/api/ConfigRefusal.ts +4 -0
  112. package/src/generated/api/DeviceKeys.ts +8 -0
  113. package/src/generated/api/Events.ts +2 -0
  114. package/src/generated/api/InstanceAddToCollection.ts +14 -0
  115. package/src/generated/api/InstanceCreate.ts +32 -0
  116. package/src/generated/api/InstanceCreated.ts +16 -0
  117. package/src/generated/api/InstanceError.ts +10 -0
  118. package/src/generated/api/InstanceRemove.ts +11 -0
  119. package/src/generated/api/InstanceRemoveFromCollection.ts +14 -0
  120. package/src/generated/api/InstanceRemoved.ts +9 -0
  121. package/src/generated/api/InstanceUpdate.ts +14 -0
  122. package/src/generated/api/InstanceUpdated.ts +3 -0
  123. package/src/generated/api/KeyClass.ts +6 -0
  124. package/src/generated/api/LogTail.ts +6 -0
  125. package/src/generated/api/LogTailParams.ts +10 -0
  126. package/src/generated/api/PerspectiveInstanceAddToCollectionParams.ts +11 -0
  127. package/src/generated/api/PerspectiveInstanceCreateParams.ts +29 -0
  128. package/src/generated/api/PerspectiveInstanceRemoveFromCollectionParams.ts +11 -0
  129. package/src/generated/api/PerspectiveInstanceRemoveParams.ts +7 -0
  130. package/src/generated/api/PerspectiveInstanceUpdateParams.ts +11 -0
  131. package/src/generated/api/Pinned.ts +7 -0
  132. package/src/generated/api/ReadOnlyReason.ts +6 -0
  133. package/src/generated/api/RefusalReason.ts +6 -0
  134. package/src/generated/api/RpcMethods.ts +30 -0
  135. package/src/generated/api/RuntimeConfig.ts +24 -0
  136. package/src/generated/api/SetConfigParams.ts +6 -0
  137. package/src/generated/api/SetConfigResult.ts +7 -0
  138. package/src/generated/api/ValidationError.ts +34 -0
  139. package/src/generated/api/ValidationProblem.ts +7 -0
  140. package/src/generated/api/WriteStep.ts +6 -0
  141. package/src/generated/api/index.ts +34 -0
  142. package/src/identity/IdentityClient.ts +20 -0
  143. package/src/model/shacl-gen.ts +4 -2
  144. package/src/neighbourhood/MeshManager.test.ts +57 -0
  145. package/src/neighbourhood/MeshManager.ts +26 -0
  146. package/src/neighbourhood/NeighbourhoodProxy.ts +7 -2
  147. package/src/neighbourhood/Session.test.ts +355 -3
  148. package/src/neighbourhood/Session.ts +170 -28
  149. package/src/perspectives/PerspectiveClient.ts +56 -0
  150. package/src/perspectives/PerspectiveProxy.test.ts +34 -0
  151. package/src/perspectives/PerspectiveProxy.ts +76 -2
  152. package/src/perspectives/WakerSubscriptionManager.test.ts +379 -1
  153. package/src/perspectives/WakerSubscriptionManager.ts +189 -41
  154. package/src/runtime/RuntimeClient.ts +25 -1
  155. package/src/shacl/SHACLFlow.test.ts +4 -2
  156. package/src/shacl/SHACLShape.test.ts +10 -3
  157. package/src/shacl/SHACLShape.ts +6 -2
@@ -5,24 +5,62 @@ import { agentOfMeshPeer, MeshManager, meshPeerId } from "./MeshManager";
5
5
  * online-status link with this predicate, its mesh peer id as source and
6
6
  * the room id as target. Other agents polling `onlineAgents()` use this
7
7
  * to discover the roster without a join message; one agent's devices each
8
- * add a link of their own to the agent's one status.
8
+ * add a link of their own to the agent's one status, with the marker
9
+ * ({@link CALL_BEATS_PREDICATE}) beside it.
9
10
  */
10
11
  const CALL_PRESENCE_PREDICATE = "ad4m://session/in-call";
11
- /** How often (ms) the mesh session polls `onlineAgents` for roster changes. */
12
- const ROSTER_POLL_INTERVAL_MS = 3000;
13
12
  /**
14
- * The mesh peer a call-presence link of `did` announces, or `null`. A link
15
- * counts only for a peer of the agent whose status carries it, so no agent
16
- * can place another in a call.
13
+ * Marker predicate: the device beats. Beside its presence link, each device
14
+ * in a mesh call writes one link with this predicate, its peer id as source
15
+ * and the room id as target, once, at join. The marker never changes; the
16
+ * beat itself travels as a `beat` message over the call's signalling
17
+ * ({@link MeshManager.beat}), every {@link BEAT_INTERVAL_MS}, and is never
18
+ * persisted. A reader leaves out a device with the marker that it has not
19
+ * heard beat for {@link PRESENCE_STALE_MS} by its own clock, counted from
20
+ * when it first saw the device if it never heard it. A presence link without
21
+ * the marker (an SDK from before the beat) never goes stale.
17
22
  */
18
- function presencePeer(did, link, roomId) {
19
- if (link?.predicate !== CALL_PRESENCE_PREDICATE || link.target !== roomId)
20
- return null;
21
- const source = link.source;
23
+ const CALL_BEATS_PREDICATE = "ad4m://session/in-call-beat";
24
+ /**
25
+ * How often (ms) a mesh device beats. Beats are best effort: a reader keeps a
26
+ * device through three lost beats in a row, with 10 s to spare for the fourth.
27
+ */
28
+ const BEAT_INTERVAL_MS = 20000;
29
+ /** How long (ms) a reader keeps a device with the marker that it has not heard beat. */
30
+ const PRESENCE_STALE_MS = 90000;
31
+ /** How often (ms) the mesh session polls `onlineAgents` for roster changes. */
32
+ const ROSTER_POLL_INTERVAL_MS = 3000;
33
+ /** `source` when it names a device of `did`, else `null`: no agent can speak for another's devices. */
34
+ function peerOf(did, source) {
22
35
  if (typeof source !== "string" || source === did || agentOfMeshPeer(source) !== did)
23
36
  return null;
24
37
  return source;
25
38
  }
39
+ /**
40
+ * The mesh peer a call-presence link or marker of `did` names for `roomId`,
41
+ * or `null`. A link counts only for a peer of the agent whose status carries
42
+ * it, so no agent can place another in a call.
43
+ */
44
+ function callPeer(did, link, roomId, predicate) {
45
+ if (link?.predicate !== predicate || link.target !== roomId)
46
+ return null;
47
+ return peerOf(did, link.source);
48
+ }
49
+ /** The devices of `did` its status links put in `roomId`, each with whether it carries the marker. */
50
+ function roomPeers(did, links, roomId) {
51
+ const peers = new Map();
52
+ for (const link of links) {
53
+ const peer = callPeer(did, link, roomId, CALL_PRESENCE_PREDICATE);
54
+ if (peer)
55
+ peers.set(peer, false);
56
+ }
57
+ for (const link of links) {
58
+ const peer = callPeer(did, link, roomId, CALL_BEATS_PREDICATE);
59
+ if (peer && peers.has(peer))
60
+ peers.set(peer, true);
61
+ }
62
+ return peers;
63
+ }
26
64
  /**
27
65
  * Where a mesh session hears that this device joined the same call again,
28
66
  * from another tab. `BroadcastChannel` reaches every tab of one browser
@@ -107,23 +145,59 @@ export function createSession(config) {
107
145
  * leaving restores if the status cannot be read then. */
108
146
  let statusBeforeCall = [];
109
147
  let announced = false;
110
- /** This agent's status links, without this device's presence link for this call. */
111
- async function ownLinksWithoutCall() {
112
- const status = ownOnlineStatus ? await ownOnlineStatus() : null;
148
+ let beatInterval = null;
149
+ /**
150
+ * Per device the roster poll found with the marker: when this session last
151
+ * heard it beat or found its pair connected, or, until then, when the poll first saw it (its own
152
+ * clock). Pruned to the devices the last poll saw.
153
+ */
154
+ const heardAt = new Map();
155
+ /** A repair of this agent's status in flight: a withdraw waits for it, so it cannot land after the withdraw. */
156
+ let repairing = null;
157
+ /** When the last repair started: a failed one is tried again only after {@link PRESENCE_STALE_MS}. */
158
+ let repairedAt = -Infinity;
159
+ /**
160
+ * Whether `peer`, carrying the marker, has not beaten for {@link PRESENCE_STALE_MS}.
161
+ * A pair connected now counts as heard: media flowing proves the peer
162
+ * alive while its beats, signals sent without delivery, may be lost.
163
+ */
164
+ function isStale(peer, now, states) {
165
+ if (!heardAt.has(peer) || states.get(peer) === "connected")
166
+ heardAt.set(peer, now);
167
+ return now - heardAt.get(peer) >= PRESENCE_STALE_MS;
168
+ }
169
+ /**
170
+ * `status`'s links without the presence links and markers of the devices
171
+ * in `drop`, and without a marker whose device has no presence link.
172
+ */
173
+ function linksWithout(status, drop) {
174
+ const all = (status?.data?.links ?? []).map((link) => link.data);
175
+ const peers = roomPeers(agentDid, all, roomId);
113
176
  const links = [];
114
- for (const link of status?.data?.links ?? []) {
115
- const l = link.data;
177
+ for (const l of all) {
116
178
  if (!l?.source || l.target === undefined)
117
179
  continue;
118
- if (presencePeer(agentDid, l, roomId) === selfPeer)
180
+ const peer = callPeer(agentDid, l, roomId, CALL_PRESENCE_PREDICATE) ?? callPeer(agentDid, l, roomId, CALL_BEATS_PREDICATE);
181
+ if (peer && (drop.has(peer) || !peers.has(peer)))
119
182
  continue;
120
183
  links.push({ source: l.source, target: l.target, ...(l.predicate ? { predicate: l.predicate } : {}) });
121
184
  }
122
185
  return links;
123
186
  }
187
+ /** This agent's status links without this device's call links. */
188
+ async function ownLinksWithoutCall() {
189
+ return linksWithout(ownOnlineStatus ? await ownOnlineStatus() : null, new Set([selfPeer]));
190
+ }
191
+ /** This device's presence link and marker for this call. */
192
+ function callLinks() {
193
+ return [
194
+ { source: selfPeer, predicate: CALL_PRESENCE_PREDICATE, target: roomId },
195
+ { source: selfPeer, predicate: CALL_BEATS_PREDICATE, target: roomId },
196
+ ];
197
+ }
124
198
  /**
125
- * Add this call's presence link to the agent's online status. Other
126
- * agents' roster polls pick it up.
199
+ * Add this call's presence link and marker to the agent's online status.
200
+ * Other agents' roster polls pick it up.
127
201
  */
128
202
  async function announceCallPresence() {
129
203
  if (!setOnlineStatus)
@@ -133,19 +207,47 @@ export function createSession(config) {
133
207
  console.warn("session: reading own status failed:", err);
134
208
  return [];
135
209
  });
136
- const presence = { source: selfPeer, predicate: CALL_PRESENCE_PREDICATE, target: roomId };
137
- await setOnlineStatus({ links: [...statusBeforeCall, presence] });
210
+ await setOnlineStatus({ links: [...statusBeforeCall, ...callLinks()] });
138
211
  announced = true;
139
212
  }
140
213
  catch (err) {
141
214
  console.warn("session: call-presence announcement failed:", err);
142
215
  }
143
216
  }
144
- /** Take this call's presence link out of the agent's status again. */
217
+ /**
218
+ * The one status write a poll may make: take out the links of this agent's
219
+ * devices in `stale`, and put this device's back if they are missing (a
220
+ * device of this agent that stopped hearing this one took them out). `own`
221
+ * is the status the poll read; an unread or unset one is never written over.
222
+ * At most one write per {@link PRESENCE_STALE_MS}, so a write that fails, or
223
+ * a sibling that keeps taking this device out, cannot write on every poll.
224
+ */
225
+ function repairOwnStatus(own, stale) {
226
+ const links = own?.data?.links;
227
+ if (!setOnlineStatus || !announced || repairing || !links)
228
+ return;
229
+ // Listed means the presence link and the marker: without the marker,
230
+ // readers would never find this device stale.
231
+ const listed = roomPeers(agentDid, links.map((l) => l.data), roomId).get(selfPeer) === true;
232
+ if (stale.size === 0 && listed)
233
+ return;
234
+ const now = Date.now();
235
+ if (now - repairedAt < PRESENCE_STALE_MS)
236
+ return;
237
+ repairedAt = now;
238
+ const write = setOnlineStatus({ links: [...linksWithout(own, new Set([...stale, selfPeer])), ...callLinks()] })
239
+ .catch((err) => console.warn("session: repairing call presence failed:", err))
240
+ .finally(() => { if (repairing === write)
241
+ repairing = null; });
242
+ repairing = write;
243
+ }
244
+ /** Take this call's presence link and marker out of the agent's status again. */
145
245
  async function withdrawCallPresence() {
146
246
  if (!setOnlineStatus || !announced)
147
247
  return;
148
248
  announced = false;
249
+ if (repairing)
250
+ await repairing;
149
251
  try {
150
252
  const links = await ownLinksWithoutCall().catch((err) => {
151
253
  console.warn("session: reading own status failed:", err);
@@ -167,6 +269,12 @@ export function createSession(config) {
167
269
  * from `ownOnlineStatus`, and passes the peers to `mesh.setRoster()`.
168
270
  * That function opens connections to new arrivals and tears down
169
271
  * connections to departed peers.
272
+ *
273
+ * A device that died without leaving keeps its link while its agent's
274
+ * other devices keep the status, so the poll leaves out a device with the
275
+ * marker ({@link CALL_BEATS_PREDICATE}) that has not beaten for
276
+ * {@link PRESENCE_STALE_MS}, and takes such devices of this agent out of
277
+ * its status ({@link repairOwnStatus}).
170
278
  */
171
279
  async function pollRoster() {
172
280
  const mesh = meshManager;
@@ -179,12 +287,24 @@ export function createSession(config) {
179
287
  // The session left while the poll was in flight.
180
288
  if (meshManager !== mesh)
181
289
  return;
290
+ const now = Date.now();
291
+ const states = mesh.peerStates();
182
292
  const inCall = new Set();
293
+ const seen = new Set();
294
+ const staleOwn = new Set();
183
295
  const collect = (did, links) => {
184
- for (const link of links ?? []) {
185
- const peer = presencePeer(did, link.data, roomId);
186
- if (peer && peer !== selfPeer)
296
+ for (const [peer, beats] of roomPeers(did, (links ?? []).map((l) => l.data), roomId)) {
297
+ if (peer === selfPeer)
298
+ continue;
299
+ if (!beats) {
300
+ inCall.add(peer);
301
+ continue;
302
+ }
303
+ seen.add(peer);
304
+ if (!isStale(peer, now, states))
187
305
  inCall.add(peer);
306
+ else if (did === agentDid)
307
+ staleOwn.add(peer);
188
308
  }
189
309
  };
190
310
  // Each agent's status is a signed perspective: its links sit
@@ -196,7 +316,11 @@ export function createSession(config) {
196
316
  collect(agent.did, agent.status?.data?.links);
197
317
  }
198
318
  collect(agentDid, own?.data?.links);
319
+ for (const peer of [...heardAt.keys()])
320
+ if (!seen.has(peer))
321
+ heardAt.delete(peer);
199
322
  mesh.setRoster([...inCall]);
323
+ repairOwnStatus(own, staleOwn);
200
324
  }
201
325
  catch (err) {
202
326
  console.warn("session: roster poll failed:", err);
@@ -205,16 +329,37 @@ export function createSession(config) {
205
329
  polling = false;
206
330
  }
207
331
  }
208
- function startRosterPolling() {
332
+ /**
333
+ * Start the roster poll and this device's beat. Each runs on its own
334
+ * timer: a poll that hangs on a slow `onlineAgents` must not stop the beat
335
+ * while media still flows.
336
+ */
337
+ function startRosterPolling(mesh) {
338
+ heardAt.clear();
339
+ repairedAt = -Infinity;
340
+ // `peer` is the verified author's DID with the device its payload names:
341
+ // a beat can only vouch for its own agent's devices. Only devices the
342
+ // poll tracks are recorded, so a stranger's beats cannot grow the map.
343
+ mesh.on("beat", (peer) => {
344
+ if (meshManager === mesh && heardAt.has(peer))
345
+ heardAt.set(peer, Date.now());
346
+ });
347
+ mesh.beat();
348
+ beatInterval = setInterval(() => mesh.beat(), BEAT_INTERVAL_MS);
209
349
  // Immediate first poll, then periodic
210
350
  void pollRoster();
211
351
  rosterInterval = setInterval(() => void pollRoster(), ROSTER_POLL_INTERVAL_MS);
212
352
  }
353
+ /** Stop the roster poll and the beat. Beats are never persisted: nothing else to undo. */
213
354
  function stopRosterPolling() {
214
355
  if (rosterInterval !== null) {
215
356
  clearInterval(rosterInterval);
216
357
  rosterInterval = null;
217
358
  }
359
+ if (beatInterval !== null) {
360
+ clearInterval(beatInterval);
361
+ beatInterval = null;
362
+ }
218
363
  }
219
364
  // ── Mesh wiring helpers ─────────────────────────────────────────
220
365
  function wireMeshEvents(mesh) {
@@ -387,7 +532,7 @@ export function createSession(config) {
387
532
  await withdrawCallPresence();
388
533
  throw new Error("Session destroyed");
389
534
  }
390
- startRosterPolling();
535
+ startRosterPolling(mesh);
391
536
  emit("topology-changed", "mesh");
392
537
  setState("active");
393
538
  return;
@@ -14,6 +14,7 @@ import type { TranscriptTurn } from "../generated/api";
14
14
  import type { AgentMessage } from "../generated/api/AgentMessage";
15
15
  import type { AgentReply } from "../generated/api/AgentReply";
16
16
  import type { JsonValue } from "../generated/api/serde_json/JsonValue";
17
+ import type { CollectionItemAdded, CollectionItemRemoved, InstanceAddToCollection, InstanceCreate, InstanceCreated, InstanceRemove, InstanceRemoveFromCollection, InstanceRemoved, InstanceUpdate, InstanceUpdated } from "../generated/api";
17
18
  import type { AddAutoProcessorConfig, InterpretationOverlayInfo, RawScope, RunInterpretationObserveOptions } from "./AutoProcessor";
18
19
  import type { FlowFireOutcome, FlowMintedReceipt, FlowOutputRef, FlowProposeResult, FlowReceiptVerdict, FlowStateEntry, FlowValidOutput } from "./FlowInstance";
19
20
  export declare class PerspectiveClient {
@@ -167,6 +168,32 @@ export declare class PerspectiveClient {
167
168
  /** Through an abstract class (#1435), the executor writes to the record's own classes. */
168
169
  updateSubject(uuid: string, subjectClass: string, expressionAddress: string, values: string, batchId?: string): Promise<boolean>;
169
170
  removeSubject(uuid: string, subjectClass: string, expressionAddress: string, batchId?: string): Promise<boolean>;
171
+ /**
172
+ * Validated writes (`perspective.instance*`): the executor checks each against the class's
173
+ * SHACL shape — each property's type, which are required, which take a single value, `sh:in`
174
+ * — before writing anything. A refused write rejects with an `RpcError` whose `data` is an
175
+ * `InstanceError` and stages nothing for that call; a shape violation is status 422 with
176
+ * `data.kind === 'validation'` and `data.errors` naming each property.
177
+ *
178
+ * With `batchId` the write is staged into that open batch and lands on its commit; the
179
+ * link reads a write does (collection membership, the remove cascade) see the batch's own
180
+ * staged work, but an instance created in the same batch is not found — instance existence
181
+ * reads committed state only, so a create followed by an update, remove or
182
+ * `instanceAddToCollection` of the new instance in one batch fails `notFound`; put a new
183
+ * instance's initial collection items on the create itself. A failure that is not a
184
+ * refusal — a store error mid-write, `failed` / `partiallyRemoved` — can leave part of the
185
+ * write staged in the batch: discard it ({@link discardBatch}) instead of committing
186
+ * it to keep the calls that succeeded.
187
+ */
188
+ instanceCreate(uuid: string, body: InstanceCreate): Promise<InstanceCreated>;
189
+ /** Sets the given single-valued properties; the others stay. See {@link instanceCreate}. */
190
+ instanceUpdate(uuid: string, body: InstanceUpdate): Promise<InstanceUpdated>;
191
+ /** Removes the instance and every link to and from it. See {@link instanceCreate}. */
192
+ instanceRemove(uuid: string, body: InstanceRemove): Promise<InstanceRemoved>;
193
+ /** Adds an item to a collection (a no-op when it is a member). See {@link instanceCreate}. */
194
+ instanceAddToCollection(uuid: string, body: InstanceAddToCollection): Promise<CollectionItemAdded>;
195
+ /** Removes an item's membership link from a collection. See {@link instanceCreate}. */
196
+ instanceRemoveFromCollection(uuid: string, body: InstanceRemoveFromCollection): Promise<CollectionItemRemoved>;
170
197
  getSubjectData(uuid: string, subjectClass: string, expressionAddress: string): Promise<string>;
171
198
  /** List the names of every SHACL shape stored in a perspective (one RPC call). */
172
199
  getShaclNames(uuid: string): Promise<string[]>;
@@ -214,6 +241,13 @@ export declare class PerspectiveClient {
214
241
  getNeighbourhoodProxy(uuid: string): NeighbourhoodProxy;
215
242
  createBatch(uuid: string): Promise<string>;
216
243
  commitBatch(uuid: string, batchId: string): Promise<LinkExpressionMutations>;
244
+ /**
245
+ * Drops an open batch without committing it — the recovery for a failed batched call:
246
+ * a failed call does not roll back the calls before it and may have staged part of its
247
+ * own work, so discard rather than commit to keep the successful calls. Resolves `true`
248
+ * when the batch was open and is now dropped.
249
+ */
250
+ discardBatch(uuid: string, batchId: string): Promise<boolean>;
217
251
  /** Register a callback that fires after a successful WebSocket reconnect.
218
252
  * Passes through to ApiClient.onReconnect(). Returns an unsubscribe function. */
219
253
  onReconnect(callback: () => void): () => void;
@@ -344,6 +344,42 @@ export class PerspectiveClient {
344
344
  async removeSubject(uuid, subjectClass, expressionAddress, batchId) {
345
345
  return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.removeSubject', { uuid, subjectClass, expressionAddress, batchId });
346
346
  }
347
+ /**
348
+ * Validated writes (`perspective.instance*`): the executor checks each against the class's
349
+ * SHACL shape — each property's type, which are required, which take a single value, `sh:in`
350
+ * — before writing anything. A refused write rejects with an `RpcError` whose `data` is an
351
+ * `InstanceError` and stages nothing for that call; a shape violation is status 422 with
352
+ * `data.kind === 'validation'` and `data.errors` naming each property.
353
+ *
354
+ * With `batchId` the write is staged into that open batch and lands on its commit; the
355
+ * link reads a write does (collection membership, the remove cascade) see the batch's own
356
+ * staged work, but an instance created in the same batch is not found — instance existence
357
+ * reads committed state only, so a create followed by an update, remove or
358
+ * `instanceAddToCollection` of the new instance in one batch fails `notFound`; put a new
359
+ * instance's initial collection items on the create itself. A failure that is not a
360
+ * refusal — a store error mid-write, `failed` / `partiallyRemoved` — can leave part of the
361
+ * write staged in the batch: discard it ({@link discardBatch}) instead of committing
362
+ * it to keep the calls that succeeded.
363
+ */
364
+ async instanceCreate(uuid, body) {
365
+ return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceCreate', { uuid, ...body });
366
+ }
367
+ /** Sets the given single-valued properties; the others stay. See {@link instanceCreate}. */
368
+ async instanceUpdate(uuid, body) {
369
+ return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceUpdate', { uuid, ...body });
370
+ }
371
+ /** Removes the instance and every link to and from it. See {@link instanceCreate}. */
372
+ async instanceRemove(uuid, body) {
373
+ return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceRemove', { uuid, ...body });
374
+ }
375
+ /** Adds an item to a collection (a no-op when it is a member). See {@link instanceCreate}. */
376
+ async instanceAddToCollection(uuid, body) {
377
+ return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceAddToCollection', { uuid, ...body });
378
+ }
379
+ /** Removes an item's membership link from a collection. See {@link instanceCreate}. */
380
+ async instanceRemoveFromCollection(uuid, body) {
381
+ return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceRemoveFromCollection', { uuid, ...body });
382
+ }
347
383
  async getSubjectData(uuid, subjectClass, expressionAddress) {
348
384
  return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.getSubjectData', { uuid, subjectClass, expressionAddress });
349
385
  }
@@ -405,6 +441,15 @@ export class PerspectiveClient {
405
441
  const diff = await __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.commitBatch', { uuid, batchId });
406
442
  return LinkExpressionMutations.fromWire(diff);
407
443
  }
444
+ /**
445
+ * Drops an open batch without committing it — the recovery for a failed batched call:
446
+ * a failed call does not roll back the calls before it and may have staged part of its
447
+ * own work, so discard rather than commit to keep the successful calls. Resolves `true`
448
+ * when the batch was open and is now dropped.
449
+ */
450
+ async discardBatch(uuid, batchId) {
451
+ return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.discardBatch', { uuid, batchId });
452
+ }
408
453
  /** Register a callback that fires after a successful WebSocket reconnect.
409
454
  * Passes through to ApiClient.onReconnect(). Returns an unsubscribe function. */
410
455
  onReconnect(callback) {
@@ -16,6 +16,7 @@ import type { TranscriptTurn } from "../generated/api";
16
16
  import type { AgentMessage } from "../generated/api/AgentMessage";
17
17
  import type { AgentReply } from "../generated/api/AgentReply";
18
18
  import type { JsonValue } from "../generated/api/serde_json/JsonValue";
19
+ import type { CollectionItemAdded, CollectionItemRemoved, InstanceAddToCollection, InstanceCreate, InstanceCreated, InstanceRemove, InstanceRemoveFromCollection, InstanceRemoved, InstanceUpdate, InstanceUpdated } from "../generated/api";
19
20
  import { SHACLShape } from "../shacl/SHACLShape";
20
21
  import { SHACLFlow } from "../shacl/SHACLFlow";
21
22
  import type { AddAutoProcessorConfig, InterpretationOverlayInfo, RawScope, RunInterpretationObserveOptions } from "./AutoProcessor";
@@ -606,6 +607,13 @@ export declare class PerspectiveProxy {
606
607
  createBatch(): Promise<string>;
607
608
  /** Commits a batch of operations */
608
609
  commitBatch(batchId: string): Promise<LinkExpressionMutations>;
610
+ /**
611
+ * Drops an open batch without committing it — the recovery for a failed batched call:
612
+ * a failed call does not roll back the calls before it and may have staged part of its
613
+ * own work, so discard rather than commit to keep the successful calls. Resolves `true`
614
+ * when the batch was open and is now dropped.
615
+ */
616
+ discardBatch(batchId: string): Promise<boolean>;
609
617
  /**
610
618
  * Retrieves and renders an Expression referenced in this perspective.
611
619
  *
@@ -900,6 +908,31 @@ export declare class PerspectiveProxy {
900
908
  * abstract class (#1435), each value is written by every class of the
901
909
  * record that the abstract class reads, under its own name. */
902
910
  updateSubject(className: string, exprAddr: string, values: Record<string, any>, batchId?: string): Promise<void>;
911
+ /**
912
+ * Creates an instance of a subject class, validated by the executor against the class's
913
+ * SHACL shape before anything is written (each property's type, which are required, which
914
+ * take a single value, `sh:in`): the same check as the MCP `instance_create` tool. A refused
915
+ * write rejects with an `RpcError` whose `data` is an `InstanceError` (status 422 and
916
+ * `kind: 'validation'` for a shape violation, with one `ValidationError` per property) and
917
+ * stages nothing. With `batchId` a non-validation failure can leave part of the write
918
+ * staged in the batch — discard it ({@link discardBatch}), don't commit it to keep
919
+ * earlier calls. An instance created in the same batch is not found — existence reads
920
+ * committed state only — so a create followed by an update, remove or
921
+ * `instanceAddToCollection` of the new instance in one batch fails `notFound`; put a new
922
+ * instance's initial collection items on the create itself.
923
+ *
924
+ * @example
925
+ * const { baseUri } = await perspective.instanceCreate({ className: "Task", properties: { title: "Write" } });
926
+ */
927
+ instanceCreate(body: InstanceCreate): Promise<InstanceCreated>;
928
+ /** Sets single-valued properties of an instance, validated; the others stay. See {@link instanceCreate}. */
929
+ instanceUpdate(body: InstanceUpdate): Promise<InstanceUpdated>;
930
+ /** Removes an instance and every link to and from it. See {@link instanceCreate}. */
931
+ instanceRemove(body: InstanceRemove): Promise<InstanceRemoved>;
932
+ /** Adds an item to a collection of an instance, validated. See {@link instanceCreate}. */
933
+ instanceAddToCollection(body: InstanceAddToCollection): Promise<CollectionItemAdded>;
934
+ /** Removes an item from a collection of an instance. See {@link instanceCreate}. */
935
+ instanceRemoveFromCollection(body: InstanceRemoveFromCollection): Promise<CollectionItemRemoved>;
903
936
  getSubjectData<T>(subjectClass: T, exprAddr: string): Promise<T>;
904
937
  /**
905
938
  * Gets actions from SHACL links for a given predicate (e.g., ad4m://constructor, ad4m://destructor).
@@ -834,6 +834,15 @@ export class PerspectiveProxy {
834
834
  invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
835
835
  return result;
836
836
  }
837
+ /**
838
+ * Drops an open batch without committing it — the recovery for a failed batched call:
839
+ * a failed call does not roll back the calls before it and may have staged part of its
840
+ * own work, so discard rather than commit to keep the successful calls. Resolves `true`
841
+ * when the batch was open and is now dropped.
842
+ */
843
+ async discardBatch(batchId) {
844
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").discardBatch(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, batchId);
845
+ }
837
846
  /**
838
847
  * Retrieves and renders an Expression referenced in this perspective.
839
848
  *
@@ -1440,6 +1449,60 @@ export class PerspectiveProxy {
1440
1449
  await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").updateSubject(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, exprAddr, JSON.stringify(values), batchId);
1441
1450
  invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
1442
1451
  }
1452
+ /**
1453
+ * Creates an instance of a subject class, validated by the executor against the class's
1454
+ * SHACL shape before anything is written (each property's type, which are required, which
1455
+ * take a single value, `sh:in`): the same check as the MCP `instance_create` tool. A refused
1456
+ * write rejects with an `RpcError` whose `data` is an `InstanceError` (status 422 and
1457
+ * `kind: 'validation'` for a shape violation, with one `ValidationError` per property) and
1458
+ * stages nothing. With `batchId` a non-validation failure can leave part of the write
1459
+ * staged in the batch — discard it ({@link discardBatch}), don't commit it to keep
1460
+ * earlier calls. An instance created in the same batch is not found — existence reads
1461
+ * committed state only — so a create followed by an update, remove or
1462
+ * `instanceAddToCollection` of the new instance in one batch fails `notFound`; put a new
1463
+ * instance's initial collection items on the create itself.
1464
+ *
1465
+ * @example
1466
+ * const { baseUri } = await perspective.instanceCreate({ className: "Task", properties: { title: "Write" } });
1467
+ */
1468
+ async instanceCreate(body) {
1469
+ const created = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").instanceCreate(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, body);
1470
+ invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
1471
+ return created;
1472
+ }
1473
+ /** Sets single-valued properties of an instance, validated; the others stay. See {@link instanceCreate}. */
1474
+ async instanceUpdate(body) {
1475
+ const updated = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").instanceUpdate(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, body);
1476
+ invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
1477
+ return updated;
1478
+ }
1479
+ /** Removes an instance and every link to and from it. See {@link instanceCreate}. */
1480
+ async instanceRemove(body) {
1481
+ // Outside a batch the links go one by one, so a rejection (`partiallyRemoved`) can
1482
+ // come after some are gone: invalidate either way.
1483
+ try {
1484
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").instanceRemove(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, body);
1485
+ }
1486
+ finally {
1487
+ invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
1488
+ }
1489
+ }
1490
+ /** Adds an item to a collection of an instance, validated. See {@link instanceCreate}. */
1491
+ async instanceAddToCollection(body) {
1492
+ const added = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").instanceAddToCollection(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, body);
1493
+ invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
1494
+ return added;
1495
+ }
1496
+ /** Removes an item from a collection of an instance. See {@link instanceCreate}. */
1497
+ async instanceRemoveFromCollection(body) {
1498
+ // Like instanceRemove, a rejection can come after some links are gone.
1499
+ try {
1500
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").instanceRemoveFromCollection(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, body);
1501
+ }
1502
+ finally {
1503
+ invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
1504
+ }
1505
+ }
1443
1506
  async getSubjectData(subjectClass, exprAddr) {
1444
1507
  if (typeof subjectClass === "string") {
1445
1508
  return JSON.parse(await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").getSubjectData(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ className: subjectClass }), exprAddr));
@@ -1940,7 +2003,9 @@ export class PerspectiveProxy {
1940
2003
  required: minCount > 0,
1941
2004
  collection: isCollection,
1942
2005
  writable,
1943
- ...(options && options.length > 0 ? { options } : {}),
2006
+ // `options: []` means "allows nothing" — keep it distinct
2007
+ // from an absent constraint.
2008
+ ...(options !== undefined ? { options } : {}),
1944
2009
  };
1945
2010
  });
1946
2011
  return { className: safeName, shapeUri, properties };
@@ -1989,7 +2054,7 @@ export class PerspectiveProxy {
1989
2054
  return {};
1990
2055
  const result = {};
1991
2056
  for (const prop of shape.properties) {
1992
- if (prop.options && prop.options.length > 0) {
2057
+ if (prop.options !== undefined) {
1993
2058
  result[prop.name] = prop.options;
1994
2059
  }
1995
2060
  }
@@ -43,6 +43,17 @@ export interface WakerSubscription {
43
43
  mentionQuery?: string;
44
44
  /** The class `mentionQuery` reads: the built-in `ad4m://Mentioning`. */
45
45
  mentionClass?: string;
46
+ /**
47
+ * Set by the manager, not the caller: whether a mention subscription's text
48
+ * query has taken its opening result, which the manager records as history.
49
+ * It persists with the subscription. Until it is set, the text query's
50
+ * opening result is history even after a restart: the persisted seen set
51
+ * may hold the mention query's records only (the subscription listened
52
+ * without its text query, #1735), so the text query's old matches would all
53
+ * wake at once. A subscription saved without it (an older version) starts
54
+ * that way too.
55
+ */
56
+ textHistoryRead?: boolean;
46
57
  neighbourhood?: string;
47
58
  }
48
59
  /**
@@ -175,7 +186,10 @@ export interface WakerSubscriptionManagerOptions {
175
186
  * the bound. Covers both `proxy.subscribe()` and `proxy.initialized`: when
176
187
  * the executor accepts the socket but never answers, neither settles, and
177
188
  * without a deadline the subscription ended up neither active nor pending,
178
- * so the re-attempt cycle never saw it (#1016).
189
+ * so the re-attempt cycle never saw it (#1016). Each query of a mention
190
+ * subscription gets its own: one whose mention query opens listens through
191
+ * it, and re-attempts a text query that did not open on its own (#1735),
192
+ * with this budget doubled per failed re-attempt, up to `maxRetryPendingMs`.
179
193
  */
180
194
  subscribeTimeoutMs?: number;
181
195
  /** First delay before offering an undelivered mention wake again (default 5000); doubles per
@@ -218,6 +232,14 @@ export declare class WakerSubscriptionManager {
218
232
  * keeps persisting them so a restart restores them (#1595).
219
233
  */
220
234
  private reopening;
235
+ /**
236
+ * Mention subscriptions listening through their mention query only, because
237
+ * their text query failed to open (#1735: a TextContent `contains` scan over a
238
+ * large neighbourhood can take longer than the handshake budget). The text
239
+ * query alone is re-attempted: `timer` is the wait before the next attempt,
240
+ * `proxy` the attempt in flight. `release()` cancels both.
241
+ */
242
+ private textRetries;
221
243
  /**
222
244
  * Cancellation tokens for in-flight `subscribe()` calls.
223
245
  *