@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
@@ -114,9 +114,11 @@ interface SessionImplConfig {
114
114
  * membership so other agents' roster polls can discover it. */
115
115
  setOnlineStatus?: (status: { links: StatusLink[] }) => Promise<boolean>
116
116
  /** This agent's current online status. The session adds its presence
117
- * link to it and takes it out again, leaving the app's own links and
118
- * the presence of this agent's other devices — which the mesh roster
119
- * reads from here too. */
117
+ * link and marker to it at join and takes them out again at leave,
118
+ * leaving the app's own links and the presence of this agent's other
119
+ * live devices — which the mesh roster reads from here too. A device of
120
+ * this agent that stopped beating is taken out once, by the poll that
121
+ * finds it stale. */
120
122
  ownOnlineStatus?: () => Promise<{ data?: { links?: { data?: Partial<StatusLink> }[] } } | null>
121
123
  /** Poll for agents currently online in the neighbourhood. The
122
124
  * session reconciles the result against its mesh connections. */
@@ -135,27 +137,68 @@ interface SessionImplConfig {
135
137
  * online-status link with this predicate, its mesh peer id as source and
136
138
  * the room id as target. Other agents polling `onlineAgents()` use this
137
139
  * to discover the roster without a join message; one agent's devices each
138
- * add a link of their own to the agent's one status.
140
+ * add a link of their own to the agent's one status, with the marker
141
+ * ({@link CALL_BEATS_PREDICATE}) beside it.
139
142
  */
140
143
  const CALL_PRESENCE_PREDICATE = "ad4m://session/in-call"
141
144
 
142
145
  type StatusLink = { source: string; predicate?: string; target: string }
143
146
 
144
- /** How often (ms) the mesh session polls `onlineAgents` for roster changes. */
145
- const ROSTER_POLL_INTERVAL_MS = 3_000
147
+ /**
148
+ * Marker predicate: the device beats. Beside its presence link, each device
149
+ * in a mesh call writes one link with this predicate, its peer id as source
150
+ * and the room id as target, once, at join. The marker never changes; the
151
+ * beat itself travels as a `beat` message over the call's signalling
152
+ * ({@link MeshManager.beat}), every {@link BEAT_INTERVAL_MS}, and is never
153
+ * persisted. A reader leaves out a device with the marker that it has not
154
+ * heard beat for {@link PRESENCE_STALE_MS} by its own clock, counted from
155
+ * when it first saw the device if it never heard it. A presence link without
156
+ * the marker (an SDK from before the beat) never goes stale.
157
+ */
158
+ const CALL_BEATS_PREDICATE = "ad4m://session/in-call-beat"
146
159
 
147
160
  /**
148
- * The mesh peer a call-presence link of `did` announces, or `null`. A link
149
- * counts only for a peer of the agent whose status carries it, so no agent
150
- * can place another in a call.
161
+ * How often (ms) a mesh device beats. Beats are best effort: a reader keeps a
162
+ * device through three lost beats in a row, with 10 s to spare for the fourth.
151
163
  */
152
- function presencePeer(did: string, link: Partial<StatusLink> | undefined, roomId: string): string | null {
153
- if (link?.predicate !== CALL_PRESENCE_PREDICATE || link.target !== roomId) return null
154
- const source = link.source
164
+ const BEAT_INTERVAL_MS = 20_000
165
+
166
+ /** How long (ms) a reader keeps a device with the marker that it has not heard beat. */
167
+ const PRESENCE_STALE_MS = 90_000
168
+
169
+ /** How often (ms) the mesh session polls `onlineAgents` for roster changes. */
170
+ const ROSTER_POLL_INTERVAL_MS = 3_000
171
+
172
+ /** `source` when it names a device of `did`, else `null`: no agent can speak for another's devices. */
173
+ function peerOf(did: string, source: unknown): string | null {
155
174
  if (typeof source !== "string" || source === did || agentOfMeshPeer(source) !== did) return null
156
175
  return source
157
176
  }
158
177
 
178
+ /**
179
+ * The mesh peer a call-presence link or marker of `did` names for `roomId`,
180
+ * or `null`. A link counts only for a peer of the agent whose status carries
181
+ * it, so no agent can place another in a call.
182
+ */
183
+ function callPeer(did: string, link: Partial<StatusLink> | undefined, roomId: string, predicate: string): string | null {
184
+ if (link?.predicate !== predicate || link.target !== roomId) return null
185
+ return peerOf(did, link.source)
186
+ }
187
+
188
+ /** The devices of `did` its status links put in `roomId`, each with whether it carries the marker. */
189
+ function roomPeers(did: string, links: (Partial<StatusLink> | undefined)[], roomId: string): Map<string, boolean> {
190
+ const peers = new Map<string, boolean>()
191
+ for (const link of links) {
192
+ const peer = callPeer(did, link, roomId, CALL_PRESENCE_PREDICATE)
193
+ if (peer) peers.set(peer, false)
194
+ }
195
+ for (const link of links) {
196
+ const peer = callPeer(did, link, roomId, CALL_BEATS_PREDICATE)
197
+ if (peer && peers.has(peer)) peers.set(peer, true)
198
+ }
199
+ return peers
200
+ }
201
+
159
202
  /**
160
203
  * Where a mesh session hears that this device joined the same call again,
161
204
  * from another tab. `BroadcastChannel` reaches every tab of one browser
@@ -248,23 +291,63 @@ export function createSession(config: SessionImplConfig): Session {
248
291
  * leaving restores if the status cannot be read then. */
249
292
  let statusBeforeCall: StatusLink[] = []
250
293
  let announced = false
294
+ let beatInterval: ReturnType<typeof setInterval> | null = null
295
+ /**
296
+ * Per device the roster poll found with the marker: when this session last
297
+ * heard it beat or found its pair connected, or, until then, when the poll first saw it (its own
298
+ * clock). Pruned to the devices the last poll saw.
299
+ */
300
+ const heardAt = new Map<string, number>()
301
+ /** A repair of this agent's status in flight: a withdraw waits for it, so it cannot land after the withdraw. */
302
+ let repairing: Promise<unknown> | null = null
303
+ /** When the last repair started: a failed one is tried again only after {@link PRESENCE_STALE_MS}. */
304
+ let repairedAt = -Infinity
251
305
 
252
- /** This agent's status links, without this device's presence link for this call. */
253
- async function ownLinksWithoutCall(): Promise<StatusLink[]> {
254
- const status = ownOnlineStatus ? await ownOnlineStatus() : null
306
+ /**
307
+ * Whether `peer`, carrying the marker, has not beaten for {@link PRESENCE_STALE_MS}.
308
+ * A pair connected now counts as heard: media flowing proves the peer
309
+ * alive while its beats, signals sent without delivery, may be lost.
310
+ */
311
+ function isStale(peer: string, now: number, states: Map<string, RTCPeerConnectionState>): boolean {
312
+ if (!heardAt.has(peer) || states.get(peer) === "connected") heardAt.set(peer, now)
313
+ return now - heardAt.get(peer)! >= PRESENCE_STALE_MS
314
+ }
315
+
316
+ type OwnStatus = { data?: { links?: { data?: Partial<StatusLink> }[] } } | null
317
+
318
+ /**
319
+ * `status`'s links without the presence links and markers of the devices
320
+ * in `drop`, and without a marker whose device has no presence link.
321
+ */
322
+ function linksWithout(status: OwnStatus, drop: Set<string>): StatusLink[] {
323
+ const all = (status?.data?.links ?? []).map((link) => link.data)
324
+ const peers = roomPeers(agentDid, all, roomId)
255
325
  const links: StatusLink[] = []
256
- for (const link of status?.data?.links ?? []) {
257
- const l = link.data
326
+ for (const l of all) {
258
327
  if (!l?.source || l.target === undefined) continue
259
- if (presencePeer(agentDid, l, roomId) === selfPeer) continue
328
+ const peer = callPeer(agentDid, l, roomId, CALL_PRESENCE_PREDICATE) ?? callPeer(agentDid, l, roomId, CALL_BEATS_PREDICATE)
329
+ if (peer && (drop.has(peer) || !peers.has(peer))) continue
260
330
  links.push({ source: l.source, target: l.target, ...(l.predicate ? { predicate: l.predicate } : {}) })
261
331
  }
262
332
  return links
263
333
  }
264
334
 
335
+ /** This agent's status links without this device's call links. */
336
+ async function ownLinksWithoutCall(): Promise<StatusLink[]> {
337
+ return linksWithout(ownOnlineStatus ? await ownOnlineStatus() : null, new Set([selfPeer]))
338
+ }
339
+
340
+ /** This device's presence link and marker for this call. */
341
+ function callLinks(): StatusLink[] {
342
+ return [
343
+ { source: selfPeer, predicate: CALL_PRESENCE_PREDICATE, target: roomId },
344
+ { source: selfPeer, predicate: CALL_BEATS_PREDICATE, target: roomId },
345
+ ]
346
+ }
347
+
265
348
  /**
266
- * Add this call's presence link to the agent's online status. Other
267
- * agents' roster polls pick it up.
349
+ * Add this call's presence link and marker to the agent's online status.
350
+ * Other agents' roster polls pick it up.
268
351
  */
269
352
  async function announceCallPresence(): Promise<void> {
270
353
  if (!setOnlineStatus) return
@@ -273,18 +356,42 @@ export function createSession(config: SessionImplConfig): Session {
273
356
  console.warn("session: reading own status failed:", err)
274
357
  return []
275
358
  })
276
- const presence = { source: selfPeer, predicate: CALL_PRESENCE_PREDICATE, target: roomId }
277
- await setOnlineStatus({ links: [...statusBeforeCall, presence] })
359
+ await setOnlineStatus({ links: [...statusBeforeCall, ...callLinks()] })
278
360
  announced = true
279
361
  } catch (err) {
280
362
  console.warn("session: call-presence announcement failed:", err)
281
363
  }
282
364
  }
283
365
 
284
- /** Take this call's presence link out of the agent's status again. */
366
+ /**
367
+ * The one status write a poll may make: take out the links of this agent's
368
+ * devices in `stale`, and put this device's back if they are missing (a
369
+ * device of this agent that stopped hearing this one took them out). `own`
370
+ * is the status the poll read; an unread or unset one is never written over.
371
+ * At most one write per {@link PRESENCE_STALE_MS}, so a write that fails, or
372
+ * a sibling that keeps taking this device out, cannot write on every poll.
373
+ */
374
+ function repairOwnStatus(own: OwnStatus, stale: Set<string>): void {
375
+ const links = own?.data?.links
376
+ if (!setOnlineStatus || !announced || repairing || !links) return
377
+ // Listed means the presence link and the marker: without the marker,
378
+ // readers would never find this device stale.
379
+ const listed = roomPeers(agentDid, links.map((l) => l.data), roomId).get(selfPeer) === true
380
+ if (stale.size === 0 && listed) return
381
+ const now = Date.now()
382
+ if (now - repairedAt < PRESENCE_STALE_MS) return
383
+ repairedAt = now
384
+ const write = setOnlineStatus({ links: [...linksWithout(own, new Set([...stale, selfPeer])), ...callLinks()] })
385
+ .catch((err) => console.warn("session: repairing call presence failed:", err))
386
+ .finally(() => { if (repairing === write) repairing = null })
387
+ repairing = write
388
+ }
389
+
390
+ /** Take this call's presence link and marker out of the agent's status again. */
285
391
  async function withdrawCallPresence(): Promise<void> {
286
392
  if (!setOnlineStatus || !announced) return
287
393
  announced = false
394
+ if (repairing) await repairing
288
395
  try {
289
396
  const links = await ownLinksWithoutCall().catch((err) => {
290
397
  console.warn("session: reading own status failed:", err)
@@ -306,6 +413,12 @@ export function createSession(config: SessionImplConfig): Session {
306
413
  * from `ownOnlineStatus`, and passes the peers to `mesh.setRoster()`.
307
414
  * That function opens connections to new arrivals and tears down
308
415
  * connections to departed peers.
416
+ *
417
+ * A device that died without leaving keeps its link while its agent's
418
+ * other devices keep the status, so the poll leaves out a device with the
419
+ * marker ({@link CALL_BEATS_PREDICATE}) that has not beaten for
420
+ * {@link PRESENCE_STALE_MS}, and takes such devices of this agent out of
421
+ * its status ({@link repairOwnStatus}).
309
422
  */
310
423
  async function pollRoster(): Promise<void> {
311
424
  const mesh = meshManager
@@ -316,11 +429,18 @@ export function createSession(config: SessionImplConfig): Session {
316
429
  const own = ownOnlineStatus ? await ownOnlineStatus() : null
317
430
  // The session left while the poll was in flight.
318
431
  if (meshManager !== mesh) return
432
+ const now = Date.now()
433
+ const states = mesh.peerStates()
319
434
  const inCall = new Set<string>()
435
+ const seen = new Set<string>()
436
+ const staleOwn = new Set<string>()
320
437
  const collect = (did: string, links: { data?: Partial<StatusLink> }[] | undefined) => {
321
- for (const link of links ?? []) {
322
- const peer = presencePeer(did, link.data, roomId)
323
- if (peer && peer !== selfPeer) inCall.add(peer)
438
+ for (const [peer, beats] of roomPeers(did, (links ?? []).map((l) => l.data), roomId)) {
439
+ if (peer === selfPeer) continue
440
+ if (!beats) { inCall.add(peer); continue }
441
+ seen.add(peer)
442
+ if (!isStale(peer, now, states)) inCall.add(peer)
443
+ else if (did === agentDid) staleOwn.add(peer)
324
444
  }
325
445
  }
326
446
  // Each agent's status is a signed perspective: its links sit
@@ -331,7 +451,9 @@ export function createSession(config: SessionImplConfig): Session {
331
451
  if (agent.did !== agentDid) collect(agent.did, agent.status?.data?.links)
332
452
  }
333
453
  collect(agentDid, own?.data?.links)
454
+ for (const peer of [...heardAt.keys()]) if (!seen.has(peer)) heardAt.delete(peer)
334
455
  mesh.setRoster([...inCall])
456
+ repairOwnStatus(own, staleOwn)
335
457
  } catch (err) {
336
458
  console.warn("session: roster poll failed:", err)
337
459
  } finally {
@@ -339,17 +461,37 @@ export function createSession(config: SessionImplConfig): Session {
339
461
  }
340
462
  }
341
463
 
342
- function startRosterPolling(): void {
464
+ /**
465
+ * Start the roster poll and this device's beat. Each runs on its own
466
+ * timer: a poll that hangs on a slow `onlineAgents` must not stop the beat
467
+ * while media still flows.
468
+ */
469
+ function startRosterPolling(mesh: MeshManager): void {
470
+ heardAt.clear()
471
+ repairedAt = -Infinity
472
+ // `peer` is the verified author's DID with the device its payload names:
473
+ // a beat can only vouch for its own agent's devices. Only devices the
474
+ // poll tracks are recorded, so a stranger's beats cannot grow the map.
475
+ mesh.on("beat", (peer: string) => {
476
+ if (meshManager === mesh && heardAt.has(peer)) heardAt.set(peer, Date.now())
477
+ })
478
+ mesh.beat()
479
+ beatInterval = setInterval(() => mesh.beat(), BEAT_INTERVAL_MS)
343
480
  // Immediate first poll, then periodic
344
481
  void pollRoster()
345
482
  rosterInterval = setInterval(() => void pollRoster(), ROSTER_POLL_INTERVAL_MS)
346
483
  }
347
484
 
485
+ /** Stop the roster poll and the beat. Beats are never persisted: nothing else to undo. */
348
486
  function stopRosterPolling(): void {
349
487
  if (rosterInterval !== null) {
350
488
  clearInterval(rosterInterval)
351
489
  rosterInterval = null
352
490
  }
491
+ if (beatInterval !== null) {
492
+ clearInterval(beatInterval)
493
+ beatInterval = null
494
+ }
353
495
  }
354
496
 
355
497
  // ── Mesh wiring helpers ─────────────────────────────────────────
@@ -518,7 +660,7 @@ export function createSession(config: SessionImplConfig): Session {
518
660
  await withdrawCallPresence()
519
661
  throw new Error("Session destroyed")
520
662
  }
521
- startRosterPolling()
663
+ startRosterPolling(mesh)
522
664
 
523
665
  emit("topology-changed", "mesh")
524
666
  setState("active")
@@ -19,6 +19,11 @@ import type { AgentMessage } from "../generated/api/AgentMessage";
19
19
  import type { AgentReply } from "../generated/api/AgentReply";
20
20
  import type { PerspectiveQueryLinksParams } from "../generated/api/PerspectiveQueryLinksParams";
21
21
  import type { JsonValue } from "../generated/api/serde_json/JsonValue";
22
+ import type {
23
+ CollectionItemAdded, CollectionItemRemoved, InstanceAddToCollection, InstanceCreate,
24
+ InstanceCreated, InstanceRemove, InstanceRemoveFromCollection, InstanceRemoved,
25
+ InstanceUpdate, InstanceUpdated,
26
+ } from "../generated/api";
22
27
  import type { AddAutoProcessorConfig, InterpretationOverlayInfo, RawScope, RunInterpretationObserveOptions } from "./AutoProcessor";
23
28
  // FlowInstance.ts owns the flow-proposal result types so they sit next to the
24
29
  // `proposeTransition()` API they describe. `import type` keeps this out of the
@@ -536,6 +541,47 @@ export class PerspectiveClient {
536
541
  )
537
542
  }
538
543
 
544
+ /**
545
+ * Validated writes (`perspective.instance*`): the executor checks each against the class's
546
+ * SHACL shape — each property's type, which are required, which take a single value, `sh:in`
547
+ * — before writing anything. A refused write rejects with an `RpcError` whose `data` is an
548
+ * `InstanceError` and stages nothing for that call; a shape violation is status 422 with
549
+ * `data.kind === 'validation'` and `data.errors` naming each property.
550
+ *
551
+ * With `batchId` the write is staged into that open batch and lands on its commit; the
552
+ * link reads a write does (collection membership, the remove cascade) see the batch's own
553
+ * staged work, but an instance created in the same batch is not found — instance existence
554
+ * reads committed state only, so a create followed by an update, remove or
555
+ * `instanceAddToCollection` of the new instance in one batch fails `notFound`; put a new
556
+ * instance's initial collection items on the create itself. A failure that is not a
557
+ * refusal — a store error mid-write, `failed` / `partiallyRemoved` — can leave part of the
558
+ * write staged in the batch: discard it ({@link discardBatch}) instead of committing
559
+ * it to keep the calls that succeeded.
560
+ */
561
+ async instanceCreate(uuid: string, body: InstanceCreate): Promise<InstanceCreated> {
562
+ return this.#apiClient.call('perspective.instanceCreate', { uuid, ...body })
563
+ }
564
+
565
+ /** Sets the given single-valued properties; the others stay. See {@link instanceCreate}. */
566
+ async instanceUpdate(uuid: string, body: InstanceUpdate): Promise<InstanceUpdated> {
567
+ return this.#apiClient.call('perspective.instanceUpdate', { uuid, ...body })
568
+ }
569
+
570
+ /** Removes the instance and every link to and from it. See {@link instanceCreate}. */
571
+ async instanceRemove(uuid: string, body: InstanceRemove): Promise<InstanceRemoved> {
572
+ return this.#apiClient.call('perspective.instanceRemove', { uuid, ...body })
573
+ }
574
+
575
+ /** Adds an item to a collection (a no-op when it is a member). See {@link instanceCreate}. */
576
+ async instanceAddToCollection(uuid: string, body: InstanceAddToCollection): Promise<CollectionItemAdded> {
577
+ return this.#apiClient.call('perspective.instanceAddToCollection', { uuid, ...body })
578
+ }
579
+
580
+ /** Removes an item's membership link from a collection. See {@link instanceCreate}. */
581
+ async instanceRemoveFromCollection(uuid: string, body: InstanceRemoveFromCollection): Promise<CollectionItemRemoved> {
582
+ return this.#apiClient.call('perspective.instanceRemoveFromCollection', { uuid, ...body })
583
+ }
584
+
539
585
  async getSubjectData(uuid: string, subjectClass: string, expressionAddress: string): Promise<string> {
540
586
  return this.#apiClient.call(
541
587
  'perspective.getSubjectData', { uuid, subjectClass, expressionAddress }
@@ -620,6 +666,16 @@ export class PerspectiveClient {
620
666
  return LinkExpressionMutations.fromWire(diff)
621
667
  }
622
668
 
669
+ /**
670
+ * Drops an open batch without committing it — the recovery for a failed batched call:
671
+ * a failed call does not roll back the calls before it and may have staged part of its
672
+ * own work, so discard rather than commit to keep the successful calls. Resolves `true`
673
+ * when the batch was open and is now dropped.
674
+ */
675
+ async discardBatch(uuid: string, batchId: string): Promise<boolean> {
676
+ return this.#apiClient.call('perspective.discardBatch', { uuid, batchId })
677
+ }
678
+
623
679
  /** Register a callback that fires after a successful WebSocket reconnect.
624
680
  * Passes through to ApiClient.onReconnect(). Returns an unsubscribe function. */
625
681
  onReconnect(callback: () => void): () => void {
@@ -522,3 +522,37 @@ describe('PerspectiveProxy write RPCs invalidate the query cache', () => {
522
522
  jest.spyOn(Date, 'now').mockRestore();
523
523
  });
524
524
  });
525
+
526
+ // Outside a batch, instanceRemove and instanceRemoveFromCollection remove
527
+ // links one by one: a failure part-way rejects the call after some links are
528
+ // already gone. A read right after must not be served from the cache.
529
+ describe('PerspectiveProxy instance writes invalidate the query cache when they fail', () => {
530
+ const query = 'SELECT ?v WHERE { <ad4m://m/1> <test://text> ?v }';
531
+ const partial = Object.assign(new Error('partiallyRemoved'), { data: { kind: 'partiallyRemoved', removed: 2 } });
532
+
533
+ function client() {
534
+ return {
535
+ querySparql: jest.fn()
536
+ .mockResolvedValueOnce([{ v: 'old' }])
537
+ .mockResolvedValueOnce([]),
538
+ instanceRemove: jest.fn().mockRejectedValue(partial),
539
+ instanceRemoveFromCollection: jest.fn().mockRejectedValue(partial),
540
+ } as any;
541
+ }
542
+
543
+ beforeEach(() => clearQueryCache());
544
+
545
+ it('after instanceRemove rejects', async () => {
546
+ const proxy = createProxy(client());
547
+ expect(await proxy.querySparql(query)).toEqual([{ v: 'old' }]);
548
+ await expect(proxy.instanceRemove({ className: 'Note', baseUri: 'ad4m://m/1' } as any)).rejects.toBe(partial);
549
+ expect(await proxy.querySparql(query)).toEqual([]);
550
+ });
551
+
552
+ it('after instanceRemoveFromCollection rejects', async () => {
553
+ const proxy = createProxy(client());
554
+ expect(await proxy.querySparql(query)).toEqual([{ v: 'old' }]);
555
+ await expect(proxy.instanceRemoveFromCollection({ className: 'Note', baseUri: 'ad4m://m/1', collection: 'tags', itemUri: 'x' } as any)).rejects.toBe(partial);
556
+ expect(await proxy.querySparql(query)).toEqual([]);
557
+ });
558
+ });
@@ -23,6 +23,11 @@ import type { TranscriptTurn } from "../generated/api";
23
23
  import type { AgentMessage } from "../generated/api/AgentMessage";
24
24
  import type { AgentReply } from "../generated/api/AgentReply";
25
25
  import type { JsonValue } from "../generated/api/serde_json/JsonValue";
26
+ import type {
27
+ CollectionItemAdded, CollectionItemRemoved, InstanceAddToCollection, InstanceCreate,
28
+ InstanceCreated, InstanceRemove, InstanceRemoveFromCollection, InstanceRemoved,
29
+ InstanceUpdate, InstanceUpdated,
30
+ } from "../generated/api";
26
31
 
27
32
  import { SHACLShape } from "../shacl/SHACLShape";
28
33
  import { SHACLFlow } from "../shacl/SHACLFlow";
@@ -959,6 +964,16 @@ export class PerspectiveProxy {
959
964
  invalidatePerspectiveCache(this.#handle.uuid);
960
965
  return result;
961
966
  }
967
+
968
+ /**
969
+ * Drops an open batch without committing it — the recovery for a failed batched call:
970
+ * a failed call does not roll back the calls before it and may have staged part of its
971
+ * own work, so discard rather than commit to keep the successful calls. Resolves `true`
972
+ * when the batch was open and is now dropped.
973
+ */
974
+ async discardBatch(batchId: string): Promise<boolean> {
975
+ return await this.#client.discardBatch(this.#handle.uuid, batchId)
976
+ }
962
977
  /**
963
978
  * Retrieves and renders an Expression referenced in this perspective.
964
979
  *
@@ -1628,6 +1643,63 @@ export class PerspectiveProxy {
1628
1643
  invalidatePerspectiveCache(this.#handle.uuid);
1629
1644
  }
1630
1645
 
1646
+ /**
1647
+ * Creates an instance of a subject class, validated by the executor against the class's
1648
+ * SHACL shape before anything is written (each property's type, which are required, which
1649
+ * take a single value, `sh:in`): the same check as the MCP `instance_create` tool. A refused
1650
+ * write rejects with an `RpcError` whose `data` is an `InstanceError` (status 422 and
1651
+ * `kind: 'validation'` for a shape violation, with one `ValidationError` per property) and
1652
+ * stages nothing. With `batchId` a non-validation failure can leave part of the write
1653
+ * staged in the batch — discard it ({@link discardBatch}), don't commit it to keep
1654
+ * earlier calls. An instance created in the same batch is not found — existence reads
1655
+ * committed state only — so a create followed by an update, remove or
1656
+ * `instanceAddToCollection` of the new instance in one batch fails `notFound`; put a new
1657
+ * instance's initial collection items on the create itself.
1658
+ *
1659
+ * @example
1660
+ * const { baseUri } = await perspective.instanceCreate({ className: "Task", properties: { title: "Write" } });
1661
+ */
1662
+ async instanceCreate(body: InstanceCreate): Promise<InstanceCreated> {
1663
+ const created = await this.#client.instanceCreate(this.#handle.uuid, body);
1664
+ invalidatePerspectiveCache(this.#handle.uuid);
1665
+ return created;
1666
+ }
1667
+
1668
+ /** Sets single-valued properties of an instance, validated; the others stay. See {@link instanceCreate}. */
1669
+ async instanceUpdate(body: InstanceUpdate): Promise<InstanceUpdated> {
1670
+ const updated = await this.#client.instanceUpdate(this.#handle.uuid, body);
1671
+ invalidatePerspectiveCache(this.#handle.uuid);
1672
+ return updated;
1673
+ }
1674
+
1675
+ /** Removes an instance and every link to and from it. See {@link instanceCreate}. */
1676
+ async instanceRemove(body: InstanceRemove): Promise<InstanceRemoved> {
1677
+ // Outside a batch the links go one by one, so a rejection (`partiallyRemoved`) can
1678
+ // come after some are gone: invalidate either way.
1679
+ try {
1680
+ return await this.#client.instanceRemove(this.#handle.uuid, body);
1681
+ } finally {
1682
+ invalidatePerspectiveCache(this.#handle.uuid);
1683
+ }
1684
+ }
1685
+
1686
+ /** Adds an item to a collection of an instance, validated. See {@link instanceCreate}. */
1687
+ async instanceAddToCollection(body: InstanceAddToCollection): Promise<CollectionItemAdded> {
1688
+ const added = await this.#client.instanceAddToCollection(this.#handle.uuid, body);
1689
+ invalidatePerspectiveCache(this.#handle.uuid);
1690
+ return added;
1691
+ }
1692
+
1693
+ /** Removes an item from a collection of an instance. See {@link instanceCreate}. */
1694
+ async instanceRemoveFromCollection(body: InstanceRemoveFromCollection): Promise<CollectionItemRemoved> {
1695
+ // Like instanceRemove, a rejection can come after some links are gone.
1696
+ try {
1697
+ return await this.#client.instanceRemoveFromCollection(this.#handle.uuid, body);
1698
+ } finally {
1699
+ invalidatePerspectiveCache(this.#handle.uuid);
1700
+ }
1701
+ }
1702
+
1631
1703
  async getSubjectData<T>(subjectClass: T, exprAddr: string): Promise<T> {
1632
1704
  if (typeof subjectClass === "string") {
1633
1705
  return JSON.parse(await this.#client.getSubjectData(this.#handle.uuid, JSON.stringify({className: subjectClass}), exprAddr))
@@ -2191,7 +2263,9 @@ export class PerspectiveProxy {
2191
2263
  required: minCount > 0,
2192
2264
  collection: isCollection,
2193
2265
  writable,
2194
- ...(options && options.length > 0 ? { options } : {}),
2266
+ // `options: []` means "allows nothing" — keep it distinct
2267
+ // from an absent constraint.
2268
+ ...(options !== undefined ? { options } : {}),
2195
2269
  };
2196
2270
  });
2197
2271
 
@@ -2241,7 +2315,7 @@ export class PerspectiveProxy {
2241
2315
  if (!shape) return {};
2242
2316
  const result: Record<string, Array<{ value: string; label?: string }>> = {};
2243
2317
  for (const prop of shape.properties) {
2244
- if (prop.options && prop.options.length > 0) {
2318
+ if (prop.options !== undefined) {
2245
2319
  result[prop.name] = prop.options;
2246
2320
  }
2247
2321
  }