@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
@@ -80,6 +80,19 @@ export type { UpdateLinkRequest } from "./UpdateLinkRequest";
80
80
  export type { UpdatePerspectiveRequest } from "./UpdatePerspectiveRequest";
81
81
  export type { VerifySignatureRequest } from "./VerifySignatureRequest";
82
82
  export type { WriteSettingsRequest } from "./WriteSettingsRequest";
83
+ // The run contract: the executor's log and its config file (runtime.logTail, runtime.config,
84
+ // runtime.setConfig, config-changed).
85
+ export type { ConfigChanged } from "./ConfigChanged";
86
+ export type { ConfigKeyInfo } from "./ConfigKeyInfo";
87
+ export type { ConfigRefusal } from "./ConfigRefusal";
88
+ export type { KeyClass } from "./KeyClass";
89
+ export type { LogTail } from "./LogTail";
90
+ export type { LogTailParams } from "./LogTailParams";
91
+ export type { Pinned } from "./Pinned";
92
+ export type { RefusalReason } from "./RefusalReason";
93
+ export type { RuntimeConfig } from "./RuntimeConfig";
94
+ export type { SetConfigParams } from "./SetConfigParams";
95
+ export type { SetConfigResult } from "./SetConfigResult";
83
96
  export type { AiCapability } from "./AiCapability";
84
97
  export type { AiDiscoverModelsParams } from "./AiDiscoverModelsParams";
85
98
  export type { AiEndpoint } from "./AiEndpoint";
@@ -102,6 +115,7 @@ export type { ClaimOfferParams } from "./ClaimOfferParams";
102
115
  export type { ClaimOfferResult } from "./ClaimOfferResult";
103
116
  export type { ClaimView } from "./ClaimView";
104
117
  export type { CosignInceptParams } from "./CosignInceptParams";
118
+ export type { DeviceKeys } from "./DeviceKeys";
105
119
  export type { DeviceView } from "./DeviceView";
106
120
  export type { DidBotScope } from "./DidBotScope";
107
121
  export type { DidDocument } from "./DidDocument";
@@ -134,6 +148,26 @@ export type { SignedRequest } from "./SignedRequest";
134
148
  export type { SkippedSource } from "./SkippedSource";
135
149
  export type { StoreBehind } from "./StoreBehind";
136
150
  export type { StoreInfo } from "./StoreInfo";
151
+ // The validated instance writes (perspective.instance*): bodies, results, and the
152
+ // error data of a refused write (RpcError.data).
153
+ export type { InstanceCreate } from "./InstanceCreate";
154
+ export type { InstanceUpdate } from "./InstanceUpdate";
155
+ export type { InstanceRemove } from "./InstanceRemove";
156
+ export type { InstanceAddToCollection } from "./InstanceAddToCollection";
157
+ export type { InstanceRemoveFromCollection } from "./InstanceRemoveFromCollection";
158
+ export type { InstanceCreated } from "./InstanceCreated";
159
+ export type { InstanceUpdated } from "./InstanceUpdated";
160
+ export type { InstanceRemoved } from "./InstanceRemoved";
161
+ export type { CollectionItemAdded } from "./CollectionItemAdded";
162
+ export type { CollectionItemRemoved } from "./CollectionItemRemoved";
163
+ export type { CollectionItems } from "./CollectionItems";
164
+ export type { InstanceError } from "./InstanceError";
165
+ export type { ValidationError } from "./ValidationError";
166
+ export type { ValidationProblem } from "./ValidationProblem";
167
+ export type { ReadOnlyReason } from "./ReadOnlyReason";
168
+ export type { Cardinality } from "./Cardinality";
169
+ export type { WriteStep } from "./WriteStep";
170
+ export type { CascadeStep } from "./CascadeStep";
137
171
  export { READ_METHODS, LONG_METHODS, OPENS_METHODS } from "./RpcMethods";
138
172
  export type { RpcMethods, RpcMethod } from "./RpcMethods";
139
173
  export { SCOPED_EVENTS } from "./Events";
@@ -1,5 +1,6 @@
1
1
  import { ApiClient } from "../apiClient";
2
2
  import type { ClaimOfferResult } from "../generated/api/ClaimOfferResult";
3
+ import type { DeviceKeys } from "../generated/api/DeviceKeys";
3
4
  import type { DeviceView } from "../generated/api/DeviceView";
4
5
  import type { DidResolutionResult } from "../generated/api/DidResolutionResult";
5
6
  import type { IdentityLog } from "../generated/api/IdentityLog";
@@ -108,4 +109,23 @@ export class IdentityClient {
108
109
  async devices(): Promise<DeviceView[]> {
109
110
  return this.#apiClient.call("identity.devices", {});
110
111
  }
112
+
113
+ /**
114
+ * A new main wallet key for this executor, so a revoked executor can link again. The old
115
+ * key stays for history. Only the operator on the executor's machine (the admin credential
116
+ * on a loopback listener). A caller without the admin credential gets 403 "Admin credential
117
+ * required"; the admin credential on a network listener gets 403 `local-only`.
118
+ */
119
+ async rekey(): Promise<DeviceKeys> {
120
+ return this.#apiClient.call("identity.rekey", {});
121
+ }
122
+
123
+ /**
124
+ * The custody channel: the main agent's device keys (public keys only), the keys a master
125
+ * key sent to this computer is sealed to. Only the admin credential on a loopback listener
126
+ * of an executor started with `--custody-channel`; any other caller gets 403.
127
+ */
128
+ async custodyStatus(): Promise<DeviceKeys> {
129
+ return this.#apiClient.call("identity.custodyStatus", {});
130
+ }
111
131
  }
@@ -201,8 +201,10 @@ export function buildSHACL(
201
201
  propShape.hasValue = propMeta.initial;
202
202
  }
203
203
 
204
- // sh:in — allowed values (enum constraint)
205
- if (propMeta.options && propMeta.options.length > 0) {
204
+ // sh:in — allowed values (enum constraint). An explicit empty list
205
+ // is kept: it denies every value, which dropping would widen to
206
+ // unconstrained.
207
+ if (propMeta.options !== undefined) {
206
208
  propShape.in = propMeta.options;
207
209
  }
208
210
 
@@ -517,6 +517,11 @@ describe("parseCallMessage", () => {
517
517
  expect(parseCallMessage(data)).toEqual(data)
518
518
  })
519
519
 
520
+ it("accepts a beat", () => {
521
+ const beat = { v: CALL_PROTOCOL_VERSION, call: "room:x", kind: "beat" as const }
522
+ expect(parseCallMessage({ ...beat, to: "*" })).toEqual(beat)
523
+ })
524
+
520
525
  it("coerces missing binary flag to false", () => {
521
526
  const raw = {
522
527
  v: CALL_PROTOCOL_VERSION,
@@ -2317,6 +2322,58 @@ describe("what a call is told about its own connections", () => {
2317
2322
 
2318
2323
  // ── Signalling before the roster ────────────────────────────────────
2319
2324
 
2325
+ describe("beats", () => {
2326
+ let bus: InMemoryBus
2327
+
2328
+ beforeEach(() => {
2329
+ bus = new InMemoryBus()
2330
+ })
2331
+
2332
+ it("sends a beat to every peer, which reports it from its sender whether the roster lists it or not", async () => {
2333
+ const alice = await makeMesh(bus, "did:alice#laptop", CALL_ID)
2334
+ const bob = await makeMesh(bus, "did:bob#phone", CALL_ID)
2335
+ const heard: string[] = []
2336
+ bob.mesh.on("beat", (peer: string) => heard.push(peer))
2337
+
2338
+ alice.mesh.beat()
2339
+ await settle()
2340
+ expect(alice.sent[alice.sent.length - 1]).toEqual({ v: CALL_PROTOCOL_VERSION, call: CALL_ID, to: "*", kind: "beat" })
2341
+ expect(heard).toEqual(["did:alice#laptop"])
2342
+
2343
+ bob.mesh.setRoster(["did:alice#laptop", "did:bob#phone"])
2344
+ alice.mesh.beat()
2345
+ await settle()
2346
+ expect(heard).toEqual(["did:alice#laptop", "did:alice#laptop"])
2347
+ expect(bob.errors).toEqual([])
2348
+ })
2349
+
2350
+ it("holds no beat for a peer the roster does not list: it is not signalling", async () => {
2351
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
2352
+ const bob = await makeMesh(bus, "did:bob", CALL_ID)
2353
+ for (let n = 0; n < 5; n += 1) alice.mesh.beat()
2354
+ await settle()
2355
+ expect((bob.mesh as unknown as { pending: Map<string, unknown[]> }).pending.size).toBe(0)
2356
+ })
2357
+
2358
+ it("reports no beat of another call", async () => {
2359
+ const alice = await makeMesh(bus, "did:alice", "call:other")
2360
+ const bob = await makeMesh(bus, "did:bob", CALL_ID)
2361
+ const heard: string[] = []
2362
+ bob.mesh.on("beat", (peer: string) => heard.push(peer))
2363
+ alice.mesh.beat()
2364
+ await settle()
2365
+ expect(heard).toEqual([])
2366
+ })
2367
+
2368
+ it("sends no beat once it has left", async () => {
2369
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
2370
+ await alice.mesh.leave()
2371
+ const sent = alice.sent.length
2372
+ alice.mesh.beat()
2373
+ expect(alice.sent.length).toBe(sent)
2374
+ })
2375
+ })
2376
+
2320
2377
  describe("signalling that arrives before the roster", () => {
2321
2378
  /**
2322
2379
  * A peer who denied the microphone has no outbound tracks and never fires
@@ -105,6 +105,12 @@ export type CallBody =
105
105
  | { kind: "reset" }
106
106
  /** Application data, relayed over signalling because the mesh has no server. SDK-only. */
107
107
  | { kind: "data"; label: string; data: string; binary: boolean }
108
+ /**
109
+ * The sender is still in the call: sent to all on a timer by the session
110
+ * (`MeshManager.beat`), reported as the `beat` event. Not persisted. An SDK
111
+ * from before it parses it to nothing and drops it without a word.
112
+ */
113
+ | { kind: "beat" }
108
114
 
109
115
  export interface CallEnvelope extends CallGenerations {
110
116
  v: number
@@ -156,6 +162,8 @@ export function parseCallMessage(payload: unknown): CallMessage | null {
156
162
 
157
163
  if (msg.kind === "reset") return { ...envelope, kind: "reset" }
158
164
 
165
+ if (msg.kind === "beat") return { ...envelope, kind: "beat" }
166
+
159
167
  if (msg.kind === "data") {
160
168
  const { label, data, binary } = msg as { label?: unknown; data?: unknown; binary?: unknown }
161
169
  if (typeof label !== "string" || typeof data !== "string") return null
@@ -361,6 +369,8 @@ export type MeshEvent =
361
369
  | "peer-state"
362
370
  /** `(did, { rung, attempts })` — a repair was attempted on this pair. */
363
371
  | "peer-recovery"
372
+ /** `(did)` — a peer of this call beat ({@link MeshManager.beat}), listed in the roster or not. */
373
+ | "beat"
364
374
  | "error"
365
375
 
366
376
  export type MeshEventCallback = (...args: any[]) => void
@@ -655,6 +665,12 @@ export class MeshManager {
655
665
  const to = (payload as { to?: unknown }).to
656
666
  if (typeof to === "string" && to !== TARGET_ALL && to !== this.selfId) return
657
667
 
668
+ // Liveness, not signalling: reported for any sender, never held.
669
+ if (message.kind === "beat") {
670
+ this.emit("beat", from)
671
+ return
672
+ }
673
+
658
674
  // Only peers the roster placed in the call. Without this, anyone on
659
675
  // the channel could open a connection by sending an offer.
660
676
  const slot = this.slots.get(from)
@@ -831,6 +847,16 @@ export class MeshManager {
831
847
  this.publish({ v: CALL_PROTOCOL_VERSION, call: this.callId, to: TARGET_ALL, kind: "data", label, data, binary })
832
848
  }
833
849
 
850
+ /**
851
+ * Tell every peer of the call that this one is still in it. Through
852
+ * {@link publish}, so a beat's publish result is counted like any other
853
+ * send. Nothing once the mesh has left.
854
+ */
855
+ beat(): void {
856
+ if (this.closed) return
857
+ this.publish({ v: CALL_PROTOCOL_VERSION, call: this.callId, to: TARGET_ALL, kind: "beat" })
858
+ }
859
+
834
860
  subscribeDataChannel(callback: (msg: SfuDataMessage) => void): () => void {
835
861
  this.dataListeners.add(callback)
836
862
  return () => this.dataListeners.delete(callback)
@@ -78,12 +78,17 @@ export class NeighbourhoodProxy {
78
78
  return await this.#client.sendSignalU(this.#pID, remoteAgentDid, payload)
79
79
  }
80
80
 
81
- /** Broadcast a signed signal to all agents in the neighbourhood. */
81
+ /**
82
+ * Broadcast a signed signal to all agents in the neighbourhood. The
83
+ * sender's own agent gets it too (its other clients hear it), so a handler
84
+ * that must not act on its own messages drops them by author or device;
85
+ * `loopback` adds a second copy for the sender's executor.
86
+ */
82
87
  async sendBroadcast(payload: Perspective, loopback: boolean = false): Promise<boolean> {
83
88
  return await this.#client.sendBroadcast(this.#pID, payload, loopback)
84
89
  }
85
90
 
86
- /** Broadcast an unsigned signal to all agents in the neighbourhood. */
91
+ /** Broadcast an unsigned signal to all agents in the neighbourhood; delivered as {@link sendBroadcast}. */
87
92
  async sendBroadcastU(payload: PerspectiveUnsignedInput, loopback: boolean = false): Promise<boolean> {
88
93
  return await this.#client.sendBroadcastU(this.#pID, payload, loopback)
89
94
  }
@@ -36,6 +36,8 @@ const mockMeshManagerInstance = {
36
36
  destroy: jest.fn().mockResolvedValue(undefined),
37
37
  getParticipants: jest.fn().mockReturnValue([]),
38
38
  setRoster: jest.fn(),
39
+ peerStates: jest.fn(() => new Map<string, string>()),
40
+ beat: jest.fn(),
39
41
  replaceTrack: jest.fn().mockResolvedValue(undefined),
40
42
  sendData: jest.fn(),
41
43
  subscribeDataChannel: jest.fn().mockReturnValue(() => {}),
@@ -97,6 +99,11 @@ function baseConfig(overrides: Record<string, unknown> = {}) {
97
99
  }
98
100
  }
99
101
 
102
+ /** The marker a mesh device writes once beside its presence link: it beats, so it can go stale. */
103
+ function markerOf(peer: string, room: string) {
104
+ return { source: peer, predicate: "ad4m://session/in-call-beat", target: room }
105
+ }
106
+
100
107
  function collectStates(session: Session): SessionState[] {
101
108
  const states: SessionState[] = []
102
109
  session.on("state-changed", (s: SessionState) => states.push(s))
@@ -293,7 +300,10 @@ describe("mesh path", () => {
293
300
  await session.join(fakeMediaStream())
294
301
 
295
302
  expect(setOnlineStatus).toHaveBeenCalledWith({
296
- links: [{ source: "did:me#this-device", predicate: "ad4m://session/in-call", target: "my-room" }],
303
+ links: [
304
+ { source: "did:me#this-device", predicate: "ad4m://session/in-call", target: "my-room" },
305
+ markerOf("did:me#this-device", "my-room"),
306
+ ],
297
307
  })
298
308
  })
299
309
 
@@ -303,6 +313,7 @@ describe("mesh path", () => {
303
313
  const appLink = { source: "did:me", predicate: "app://mood", target: "literal:string:busy" }
304
314
  const inCall = { source: "did:me#this-device", predicate: "ad4m://session/in-call", target: "my-room" }
305
315
  const phoneInCall = { source: "did:me#phone", predicate: "ad4m://session/in-call", target: "my-room" }
316
+ const beat = markerOf("did:me#this-device", "my-room")
306
317
  const statusWith = (...links: object[]) => ({ data: { links: links.map((data) => ({ data })) } })
307
318
 
308
319
  function presenceSession(ownOnlineStatus: jest.Mock) {
@@ -321,7 +332,7 @@ describe("mesh path", () => {
321
332
  it("adds the presence link to the app's links on join", async () => {
322
333
  const { session, setOnlineStatus } = presenceSession(jest.fn().mockResolvedValue(statusWith(appLink)))
323
334
  await session.join(fakeMediaStream())
324
- expect(setOnlineStatus).toHaveBeenLastCalledWith({ links: [appLink, inCall] })
335
+ expect(setOnlineStatus).toHaveBeenLastCalledWith({ links: [appLink, inCall, beat] })
325
336
  })
326
337
 
327
338
  it("takes the presence link out on leave and keeps the app's links", async () => {
@@ -337,7 +348,7 @@ describe("mesh path", () => {
337
348
  const own = jest.fn().mockResolvedValue(statusWith(appLink, phoneInCall))
338
349
  const { session, setOnlineStatus } = presenceSession(own)
339
350
  await session.join(fakeMediaStream())
340
- expect(setOnlineStatus).toHaveBeenLastCalledWith({ links: [appLink, phoneInCall, inCall] })
351
+ expect(setOnlineStatus).toHaveBeenLastCalledWith({ links: [appLink, phoneInCall, inCall, beat] })
341
352
  own.mockResolvedValue(statusWith(appLink, phoneInCall, inCall))
342
353
  await session.leave()
343
354
  expect(setOnlineStatus).toHaveBeenLastCalledWith({ links: [appLink, phoneInCall] })
@@ -1155,3 +1166,344 @@ describe("mesh roster polling edge cases", () => {
1155
1166
  consoleWarn.mockRestore()
1156
1167
  })
1157
1168
  })
1169
+
1170
+ // A device can die without leaving (a crash, a closed browser, a lost network).
1171
+ // Its links stay in its agent's one status for as long as another device of
1172
+ // the agent keeps that status. So each device beats over the call's signalling
1173
+ // (never into the status), and a reader leaves out a device that carries the
1174
+ // marker but has not beaten for the stale bound.
1175
+ describe("a mesh device that dies without leaving", () => {
1176
+ const ROOM = "beat-room"
1177
+ /** The bounds the session works to (Session.ts): beat, staleness, roster poll. */
1178
+ const BEAT_MS = 20_000
1179
+ const STALE_MS = 90_000
1180
+ const POLL_MS = 3_000
1181
+ const realSetTimeout = setTimeout
1182
+
1183
+ type Link = { source: string; predicate: string; target: string }
1184
+ const presence = (peer: string): Link => ({ source: peer, predicate: "ad4m://session/in-call", target: ROOM })
1185
+ const marker = (peer: string): Link => ({ source: peer, predicate: "ad4m://session/in-call-beat", target: ROOM })
1186
+ const statusOf = (links: Link[]) => ({ data: { links: links.map((data) => ({ data })) } })
1187
+ const ME = "did:me#this-device"
1188
+
1189
+ /** Agents' statuses as an executor holds them; this session is `did:me`'s device `this-device`. */
1190
+ function world(overrides: Record<string, unknown> = {}) {
1191
+ const statuses = new Map<string, Link[]>()
1192
+ /** While set, this agent's status writes wait for it. */
1193
+ let gate: Promise<void> | null = null
1194
+ const setOnlineStatus = jest.fn(async ({ links }: { links: Link[] }) => {
1195
+ if (gate) await gate
1196
+ statuses.set("did:me", links)
1197
+ return true
1198
+ })
1199
+ const ownOnlineStatus = jest.fn(async () => (statuses.has("did:me") ? statusOf(statuses.get("did:me")!) : null))
1200
+ const onlineAgents = jest.fn(async () =>
1201
+ [...statuses].filter(([did]) => did !== "did:me").map(([did, links]) => ({ did, status: statusOf(links) })))
1202
+ /** A device of `did` writes its links into the agent's status, keeping everyone else's. */
1203
+ const write = (did: string, peer: string, ...links: Link[]) =>
1204
+ statuses.set(did, [...(statuses.get(did) ?? []).filter((l) => l.source !== peer), ...links])
1205
+ /** A beat reaching this session from `peer`: the sender the channel verified (author DID, payload device). */
1206
+ const beatFrom = (peer: string) => {
1207
+ for (const [event, handler] of mockMeshManagerInstance.on.mock.calls) if (event === "beat") handler(peer)
1208
+ }
1209
+ /** A live device of `did` on this SDK: announces with the marker once, then beats. */
1210
+ const live = (did: string, peer: string) => {
1211
+ write(did, peer, presence(peer), marker(peer))
1212
+ setInterval(() => beatFrom(peer), BEAT_MS)
1213
+ }
1214
+ const session = createSession(baseConfig({
1215
+ topology: "mesh",
1216
+ channel: fakeChannel(),
1217
+ setOnlineStatus,
1218
+ ownOnlineStatus,
1219
+ onlineAgents,
1220
+ roomId: ROOM,
1221
+ agentDid: "did:me",
1222
+ ...overrides,
1223
+ }))
1224
+ /** The last roster the mesh got, sorted. */
1225
+ const roster = (): string[] => [...(mockMeshManagerInstance.setRoster.mock.calls.at(-1)?.[0] ?? [])].sort()
1226
+ const own = (): Link[] => statuses.get("did:me") ?? []
1227
+ const beats = () => mockMeshManagerInstance.beat.mock.calls.length
1228
+ const writes = () => setOnlineStatus.mock.calls.length
1229
+ const hold = () => {
1230
+ let open!: () => void
1231
+ gate = new Promise((resolve) => { open = resolve })
1232
+ return () => { gate = null; open() }
1233
+ }
1234
+ return { session, statuses, setOnlineStatus, write, beatFrom, live, roster, own, beats, writes, hold }
1235
+ }
1236
+
1237
+ beforeEach(() => { jest.useFakeTimers() })
1238
+ afterEach(() => {
1239
+ jest.clearAllTimers()
1240
+ jest.useRealTimers()
1241
+ mockMeshManagerInstance.peerStates.mockImplementation(() => new Map<string, string>())
1242
+ })
1243
+
1244
+ it("announces the presence link and the marker once, then beats at once and every beat interval without writing the status", async () => {
1245
+ const w = world()
1246
+ w.live("did:bob", "did:bob#desk")
1247
+ await w.session.join(fakeMediaStream())
1248
+ expect(w.own()).toEqual([presence(ME), marker(ME)])
1249
+ expect(w.beats()).toBe(1)
1250
+
1251
+ await jest.advanceTimersByTimeAsync(10 * BEAT_MS)
1252
+ expect(w.beats()).toBe(11)
1253
+ expect(w.writes()).toBe(1)
1254
+ expect(w.roster()).toEqual(["did:bob#desk"])
1255
+
1256
+ await w.session.leave()
1257
+ expect(w.writes()).toBe(2)
1258
+ expect(w.own()).toEqual([])
1259
+ })
1260
+
1261
+ it("keeps beating while the roster poll hangs on onlineAgents", async () => {
1262
+ const w = world({ onlineAgents: jest.fn(() => new Promise(() => {})) })
1263
+ await w.session.join(fakeMediaStream())
1264
+ await jest.advanceTimersByTimeAsync(5 * BEAT_MS)
1265
+ expect(w.beats()).toBe(6)
1266
+ expect(w.writes()).toBe(1)
1267
+ await w.session.leave()
1268
+ })
1269
+
1270
+ it("leaves out another agent's device whose beats stopped, never an older SDK's, and a new beat brings it back", async () => {
1271
+ const w = world()
1272
+ w.live("did:bob", "did:bob#desk")
1273
+ w.write("did:bob", "did:bob#laptop", presence("did:bob#laptop"), marker("did:bob#laptop"))
1274
+ // A device on an SDK from before the beat writes no marker and sends no beat.
1275
+ w.write("did:carol", "did:carol#old", presence("did:carol#old"))
1276
+ await w.session.join(fakeMediaStream())
1277
+ // The laptop's last beat.
1278
+ w.beatFrom("did:bob#laptop")
1279
+
1280
+ await jest.advanceTimersByTimeAsync(STALE_MS - POLL_MS)
1281
+ expect(w.roster()).toEqual(["did:bob#desk", "did:bob#laptop", "did:carol#old"])
1282
+ await jest.advanceTimersByTimeAsync(POLL_MS)
1283
+ expect(w.roster()).toEqual(["did:bob#desk", "did:carol#old"])
1284
+
1285
+ await jest.advanceTimersByTimeAsync(10 * 60_000)
1286
+ expect(w.roster()).toEqual(["did:bob#desk", "did:carol#old"])
1287
+
1288
+ w.beatFrom("did:bob#laptop")
1289
+ await jest.advanceTimersByTimeAsync(POLL_MS)
1290
+ expect(w.roster()).toEqual(["did:bob#desk", "did:bob#laptop", "did:carol#old"])
1291
+ // No status of another agent is ever written.
1292
+ expect(w.writes()).toBe(1)
1293
+ await w.session.leave()
1294
+ })
1295
+
1296
+ it("keeps a device with the marker that it has never heard for the stale bound from when it first saw it", async () => {
1297
+ const w = world()
1298
+ w.write("did:bob", "did:bob#quiet", presence("did:bob#quiet"), marker("did:bob#quiet"))
1299
+ await w.session.join(fakeMediaStream())
1300
+ await jest.advanceTimersByTimeAsync(STALE_MS - POLL_MS)
1301
+ expect(w.roster()).toEqual(["did:bob#quiet"])
1302
+ await jest.advanceTimersByTimeAsync(POLL_MS)
1303
+ expect(w.roster()).toEqual([])
1304
+ await w.session.leave()
1305
+ })
1306
+
1307
+ it("keeps a device that lost three beats in a row", async () => {
1308
+ const w = world()
1309
+ w.write("did:bob", "did:bob#lossy", presence("did:bob#lossy"), marker("did:bob#lossy"))
1310
+ await w.session.join(fakeMediaStream())
1311
+ w.beatFrom("did:bob#lossy")
1312
+ // Its beats at 20, 40 and 60 s are lost; the one at 80 s arrives.
1313
+ await jest.advanceTimersByTimeAsync(4 * BEAT_MS)
1314
+ w.beatFrom("did:bob#lossy")
1315
+ await jest.advanceTimersByTimeAsync(STALE_MS - 4 * BEAT_MS + POLL_MS)
1316
+ expect(w.roster()).toEqual(["did:bob#lossy"])
1317
+ await w.session.leave()
1318
+ })
1319
+
1320
+ it("takes no agent's beat for another agent's device, and makes no device of a beat", async () => {
1321
+ const w = world()
1322
+ w.write("did:me", "did:me#phone", presence("did:me#phone"), marker("did:me#phone"))
1323
+ w.write("did:carol", "did:carol#desk", presence("did:carol#desk"), marker("did:carol#desk"))
1324
+ // Bob's status names devices of Carol's and of this agent's: neither counts.
1325
+ w.write("did:bob", "did:bob", presence("did:carol#tablet"), marker("did:carol#tablet"), presence("did:me#tablet"))
1326
+ await w.session.join(fakeMediaStream())
1327
+ // Bob beats under their device ids: the channel names him as the sender,
1328
+ // so each beat is one of his own devices, and one without presence.
1329
+ const forge = () => ["did:bob#phone", "did:bob#desk", "did:bob#tablet", "did:bob#ghost"].forEach(w.beatFrom)
1330
+ forge()
1331
+ setInterval(forge, BEAT_MS / 2)
1332
+ await jest.advanceTimersByTimeAsync(POLL_MS)
1333
+ expect(w.roster()).toEqual(["did:carol#desk", "did:me#phone"])
1334
+
1335
+ await jest.advanceTimersByTimeAsync(STALE_MS)
1336
+ expect(w.roster()).toEqual([])
1337
+ await w.session.leave()
1338
+ })
1339
+
1340
+ it("takes its agent's dead device out of the roster and of the status in one write, keeping every other link", async () => {
1341
+ const appLink = { source: "did:me", predicate: "app://mood", target: "literal:string:busy" }
1342
+ const w = world()
1343
+ w.statuses.set("did:me", [appLink])
1344
+ w.live("did:me", "did:me#tablet")
1345
+ w.write("did:me", "did:me#phone", presence("did:me#phone"), marker("did:me#phone"))
1346
+ await w.session.join(fakeMediaStream())
1347
+ expect(w.writes()).toBe(1)
1348
+
1349
+ await jest.advanceTimersByTimeAsync(STALE_MS - POLL_MS)
1350
+ expect(w.roster()).toEqual(["did:me#phone", "did:me#tablet"])
1351
+ expect(w.writes()).toBe(1)
1352
+
1353
+ await jest.advanceTimersByTimeAsync(POLL_MS)
1354
+ expect(w.roster()).toEqual(["did:me#tablet"])
1355
+ expect(w.writes()).toBe(2)
1356
+ expect(w.own()).toHaveLength(5)
1357
+ expect(w.own()).toEqual(expect.arrayContaining([
1358
+ appLink, presence("did:me#tablet"), marker("did:me#tablet"), presence(ME), marker(ME),
1359
+ ]))
1360
+
1361
+ // Nothing changes after: no more writes.
1362
+ await jest.advanceTimersByTimeAsync(10 * 60_000)
1363
+ expect(w.writes()).toBe(2)
1364
+ expect(w.roster()).toEqual(["did:me#tablet"])
1365
+
1366
+ await w.session.leave()
1367
+ expect(w.writes()).toBe(3)
1368
+ expect(w.own()).toEqual(expect.arrayContaining([appLink, presence("did:me#tablet"), marker("did:me#tablet")]))
1369
+ expect(w.own()).toHaveLength(3)
1370
+ })
1371
+
1372
+ it("keeps a peer whose pair is connected without beats, and drops it once disconnected and still silent", async () => {
1373
+ const states = new Map<string, string>()
1374
+ mockMeshManagerInstance.peerStates.mockImplementation(() => new Map(states))
1375
+ const w = world()
1376
+ w.write("did:bob", "did:bob#desk", presence("did:bob#desk"), marker("did:bob#desk"))
1377
+ w.write("did:me", "did:me#phone", presence("did:me#phone"), marker("did:me#phone"))
1378
+ await w.session.join(fakeMediaStream())
1379
+ // Signals fail: no beat ever arrives, but media flows on both pairs.
1380
+ states.set("did:bob#desk", "connected")
1381
+ states.set("did:me#phone", "connected")
1382
+ await jest.advanceTimersByTimeAsync(2 * STALE_MS)
1383
+ expect(w.roster()).toEqual(["did:bob#desk", "did:me#phone"])
1384
+ expect(w.writes()).toBe(1)
1385
+
1386
+ states.set("did:bob#desk", "disconnected")
1387
+ states.set("did:me#phone", "failed")
1388
+ await jest.advanceTimersByTimeAsync(STALE_MS - POLL_MS)
1389
+ expect(w.roster()).toEqual(["did:bob#desk", "did:me#phone"])
1390
+ await jest.advanceTimersByTimeAsync(2 * POLL_MS)
1391
+ expect(w.roster()).toEqual([])
1392
+ expect(w.writes()).toBe(2)
1393
+ expect(w.own()).toEqual([presence(ME), marker(ME)])
1394
+ await w.session.leave()
1395
+ })
1396
+
1397
+ it("puts its marker back when the status keeps its presence link but lost the marker", async () => {
1398
+ const appLink = { source: "did:me", predicate: "app://mood", target: "literal:string:busy" }
1399
+ const w = world()
1400
+ await w.session.join(fakeMediaStream())
1401
+ w.statuses.set("did:me", [appLink, presence(ME)])
1402
+ await jest.advanceTimersByTimeAsync(POLL_MS)
1403
+ expect(w.writes()).toBe(2)
1404
+ expect(w.own()).toEqual([appLink, presence(ME), marker(ME)])
1405
+ await jest.advanceTimersByTimeAsync(10 * 60_000)
1406
+ expect(w.writes()).toBe(2)
1407
+ await w.session.leave()
1408
+ })
1409
+
1410
+ it("tries a failed cleanup again only after the stale bound", async () => {
1411
+ const consoleWarn = jest.spyOn(console, "warn").mockImplementation()
1412
+ const w = world()
1413
+ w.write("did:me", "did:me#phone", presence("did:me#phone"), marker("did:me#phone"))
1414
+ await w.session.join(fakeMediaStream())
1415
+ w.setOnlineStatus.mockRejectedValue(new Error("store down"))
1416
+ await jest.advanceTimersByTimeAsync(STALE_MS)
1417
+ expect(w.writes()).toBe(2)
1418
+ await jest.advanceTimersByTimeAsync(STALE_MS - POLL_MS)
1419
+ expect(w.writes()).toBe(2)
1420
+ await jest.advanceTimersByTimeAsync(POLL_MS)
1421
+ expect(w.writes()).toBe(3)
1422
+ await w.session.leave()
1423
+ consoleWarn.mockRestore()
1424
+ })
1425
+
1426
+ it("puts its own links back, once, when another device took them out of the status", async () => {
1427
+ const appLink = { source: "did:me", predicate: "app://mood", target: "literal:string:busy" }
1428
+ const w = world()
1429
+ await w.session.join(fakeMediaStream())
1430
+ // A device of this agent that missed this one's beats took its links out.
1431
+ w.statuses.set("did:me", [appLink])
1432
+ await jest.advanceTimersByTimeAsync(POLL_MS)
1433
+ expect(w.writes()).toBe(2)
1434
+ expect(w.own()).toEqual([appLink, presence(ME), marker(ME)])
1435
+ await jest.advanceTimersByTimeAsync(10 * 60_000)
1436
+ expect(w.writes()).toBe(2)
1437
+ await w.session.leave()
1438
+ })
1439
+
1440
+ it("writes nothing while its agent's status reads as none", async () => {
1441
+ const w = world()
1442
+ w.live("did:bob", "did:bob#desk")
1443
+ await w.session.join(fakeMediaStream())
1444
+ w.statuses.delete("did:me")
1445
+ await jest.advanceTimersByTimeAsync(10 * 60_000)
1446
+ expect(w.writes()).toBe(1)
1447
+ expect(w.roster()).toEqual(["did:bob#desk"])
1448
+ await w.session.leave()
1449
+ })
1450
+
1451
+ it("withdraws after a cleanup write still in flight, so the withdraw is the last write", async () => {
1452
+ const appLink = { source: "did:me", predicate: "app://mood", target: "literal:string:busy" }
1453
+ const w = world()
1454
+ w.statuses.set("did:me", [appLink])
1455
+ w.write("did:me", "did:me#phone", presence("did:me#phone"), marker("did:me#phone"))
1456
+ await w.session.join(fakeMediaStream())
1457
+ const open = w.hold()
1458
+ await jest.advanceTimersByTimeAsync(STALE_MS)
1459
+ expect(w.writes()).toBe(2)
1460
+ const leaving = w.session.leave()
1461
+ await jest.advanceTimersByTimeAsync(0)
1462
+ open()
1463
+ await leaving
1464
+ expect(w.own()).toEqual([appLink])
1465
+ })
1466
+
1467
+ /** Join, see a beat, end the call with `end`, and count beats and status writes for long after. */
1468
+ async function after(end: (w: ReturnType<typeof world>) => Promise<void>) {
1469
+ const w = world()
1470
+ await w.session.join(fakeMediaStream())
1471
+ await jest.advanceTimersByTimeAsync(BEAT_MS)
1472
+ expect(w.beats()).toBe(2)
1473
+ await end(w)
1474
+ const beats = w.beats()
1475
+ const writes = w.writes()
1476
+ await jest.advanceTimersByTimeAsync(10 * BEAT_MS)
1477
+ return { w, beats: w.beats() - beats, writes: w.writes() - writes }
1478
+ }
1479
+
1480
+ it("stops beating on leave", async () => {
1481
+ const { w, beats, writes } = await after((w) => w.session.leave())
1482
+ expect([beats, writes]).toEqual([0, 0])
1483
+ expect(w.own()).toEqual([])
1484
+ })
1485
+
1486
+ it("stops beating on destroy", async () => {
1487
+ const { w, beats, writes } = await after((w) => w.session.destroy())
1488
+ expect([beats, writes]).toEqual([0, 0])
1489
+ expect(w.own()).toEqual([])
1490
+ })
1491
+
1492
+ it("stops beating when another tab of this device takes the call over", async () => {
1493
+ let later: Session | null = null
1494
+ const laterMesh = { ...mockMeshManagerInstance, beat: jest.fn() }
1495
+ const { w, beats, writes } = await after(async () => {
1496
+ ;(MeshManager as unknown as jest.Mock).mockImplementationOnce(() => laterMesh)
1497
+ later = createSession(baseConfig({ topology: "mesh", channel: fakeChannel(), roomId: ROOM, agentDid: "did:me" }))
1498
+ await later.join(fakeMediaStream())
1499
+ // BroadcastChannel delivers on the real event loop.
1500
+ await new Promise((r) => realSetTimeout(r, 20))
1501
+ })
1502
+ expect(w.session.getState()).toBe("idle")
1503
+ expect([beats, writes]).toEqual([0, 0])
1504
+ // The tab that took over beats for the device.
1505
+ expect(laterMesh.beat.mock.calls.length).toBeGreaterThan(1)
1506
+ await later!.destroy()
1507
+ await w.session.destroy()
1508
+ })
1509
+ })