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

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 (153) 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/Cardinality.d.ts +7 -0
  6. package/lib/src/generated/api/Cardinality.js +2 -0
  7. package/lib/src/generated/api/CascadeStep.d.ts +12 -0
  8. package/lib/src/generated/api/CascadeStep.js +2 -0
  9. package/lib/src/generated/api/CollectionItemAdded.d.ts +14 -0
  10. package/lib/src/generated/api/CollectionItemAdded.js +2 -0
  11. package/lib/src/generated/api/CollectionItemRemoved.d.ts +12 -0
  12. package/lib/src/generated/api/CollectionItemRemoved.js +2 -0
  13. package/lib/src/generated/api/CollectionItems.d.ts +7 -0
  14. package/lib/src/generated/api/CollectionItems.js +2 -0
  15. package/lib/src/generated/api/ConfigChanged.d.ts +8 -0
  16. package/lib/src/generated/api/ConfigChanged.js +2 -0
  17. package/lib/src/generated/api/ConfigKeyInfo.d.ts +10 -0
  18. package/lib/src/generated/api/ConfigKeyInfo.js +1 -0
  19. package/lib/src/generated/api/ConfigRefusal.d.ts +6 -0
  20. package/lib/src/generated/api/ConfigRefusal.js +1 -0
  21. package/lib/src/generated/api/DeviceKeys.d.ts +9 -0
  22. package/lib/src/generated/api/DeviceKeys.js +2 -0
  23. package/lib/src/generated/api/Events.d.ts +2 -0
  24. package/lib/src/generated/api/InstanceAddToCollection.d.ts +16 -0
  25. package/lib/src/generated/api/InstanceAddToCollection.js +2 -0
  26. package/lib/src/generated/api/InstanceCreate.d.ts +31 -0
  27. package/lib/src/generated/api/InstanceCreate.js +2 -0
  28. package/lib/src/generated/api/InstanceCreated.d.ts +17 -0
  29. package/lib/src/generated/api/InstanceCreated.js +1 -0
  30. package/lib/src/generated/api/InstanceError.d.ts +55 -0
  31. package/lib/src/generated/api/InstanceError.js +1 -0
  32. package/lib/src/generated/api/InstanceRemove.d.ts +12 -0
  33. package/lib/src/generated/api/InstanceRemove.js +2 -0
  34. package/lib/src/generated/api/InstanceRemoveFromCollection.d.ts +16 -0
  35. package/lib/src/generated/api/InstanceRemoveFromCollection.js +2 -0
  36. package/lib/src/generated/api/InstanceRemoved.d.ts +10 -0
  37. package/lib/src/generated/api/InstanceRemoved.js +2 -0
  38. package/lib/src/generated/api/InstanceUpdate.d.ts +15 -0
  39. package/lib/src/generated/api/InstanceUpdate.js +2 -0
  40. package/lib/src/generated/api/InstanceUpdated.d.ts +5 -0
  41. package/lib/src/generated/api/InstanceUpdated.js +2 -0
  42. package/lib/src/generated/api/KeyClass.d.ts +4 -0
  43. package/lib/src/generated/api/KeyClass.js +2 -0
  44. package/lib/src/generated/api/LogTail.d.ts +6 -0
  45. package/lib/src/generated/api/LogTail.js +2 -0
  46. package/lib/src/generated/api/LogTailParams.d.ts +9 -0
  47. package/lib/src/generated/api/LogTailParams.js +2 -0
  48. package/lib/src/generated/api/PerspectiveInstanceAddToCollectionParams.d.ts +14 -0
  49. package/lib/src/generated/api/PerspectiveInstanceAddToCollectionParams.js +2 -0
  50. package/lib/src/generated/api/PerspectiveInstanceCreateParams.d.ts +29 -0
  51. package/lib/src/generated/api/PerspectiveInstanceCreateParams.js +2 -0
  52. package/lib/src/generated/api/PerspectiveInstanceRemoveFromCollectionParams.d.ts +14 -0
  53. package/lib/src/generated/api/PerspectiveInstanceRemoveFromCollectionParams.js +2 -0
  54. package/lib/src/generated/api/PerspectiveInstanceRemoveParams.d.ts +9 -0
  55. package/lib/src/generated/api/PerspectiveInstanceRemoveParams.js +2 -0
  56. package/lib/src/generated/api/PerspectiveInstanceUpdateParams.d.ts +13 -0
  57. package/lib/src/generated/api/PerspectiveInstanceUpdateParams.js +2 -0
  58. package/lib/src/generated/api/Pinned.d.ts +5 -0
  59. package/lib/src/generated/api/Pinned.js +2 -0
  60. package/lib/src/generated/api/ReadOnlyReason.d.ts +4 -0
  61. package/lib/src/generated/api/ReadOnlyReason.js +2 -0
  62. package/lib/src/generated/api/RefusalReason.d.ts +4 -0
  63. package/lib/src/generated/api/RefusalReason.js +2 -0
  64. package/lib/src/generated/api/RpcMethods.d.ts +60 -0
  65. package/lib/src/generated/api/RpcMethods.js +3 -0
  66. package/lib/src/generated/api/RuntimeConfig.d.ts +23 -0
  67. package/lib/src/generated/api/RuntimeConfig.js +1 -0
  68. package/lib/src/generated/api/SetConfigParams.d.ts +7 -0
  69. package/lib/src/generated/api/SetConfigParams.js +2 -0
  70. package/lib/src/generated/api/SetConfigResult.d.ts +8 -0
  71. package/lib/src/generated/api/SetConfigResult.js +1 -0
  72. package/lib/src/generated/api/ValidationError.d.ts +34 -0
  73. package/lib/src/generated/api/ValidationError.js +1 -0
  74. package/lib/src/generated/api/ValidationProblem.d.ts +34 -0
  75. package/lib/src/generated/api/ValidationProblem.js +1 -0
  76. package/lib/src/generated/api/WriteStep.d.ts +37 -0
  77. package/lib/src/generated/api/WriteStep.js +2 -0
  78. package/lib/src/generated/api/index.d.ts +30 -0
  79. package/lib/src/identity/IdentityClient.d.ts +14 -0
  80. package/lib/src/identity/IdentityClient.js +17 -0
  81. package/lib/src/model/shacl-gen.js +4 -2
  82. package/lib/src/neighbourhood/MeshManager.d.ts +17 -1
  83. package/lib/src/neighbourhood/MeshManager.js +17 -0
  84. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +7 -2
  85. package/lib/src/neighbourhood/NeighbourhoodProxy.js +7 -2
  86. package/lib/src/neighbourhood/Session.d.ts +5 -3
  87. package/lib/src/neighbourhood/Session.js +171 -26
  88. package/lib/src/perspectives/PerspectiveClient.d.ts +34 -0
  89. package/lib/src/perspectives/PerspectiveClient.js +45 -0
  90. package/lib/src/perspectives/PerspectiveProxy.d.ts +33 -0
  91. package/lib/src/perspectives/PerspectiveProxy.js +67 -2
  92. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +23 -1
  93. package/lib/src/perspectives/WakerSubscriptionManager.js +187 -36
  94. package/lib/src/runtime/RuntimeClient.d.ts +13 -1
  95. package/lib/src/runtime/RuntimeClient.js +20 -0
  96. package/lib/src/shacl/SHACLShape.js +6 -2
  97. package/package.json +2 -2
  98. package/src/Ad4mClient.test.ts +118 -2
  99. package/src/apiClient.ts +10 -4
  100. package/src/generated/api/Cardinality.ts +6 -0
  101. package/src/generated/api/CascadeStep.ts +6 -0
  102. package/src/generated/api/CollectionItemAdded.ts +11 -0
  103. package/src/generated/api/CollectionItemRemoved.ts +9 -0
  104. package/src/generated/api/CollectionItems.ts +6 -0
  105. package/src/generated/api/ConfigChanged.ts +7 -0
  106. package/src/generated/api/ConfigKeyInfo.ts +8 -0
  107. package/src/generated/api/ConfigRefusal.ts +4 -0
  108. package/src/generated/api/DeviceKeys.ts +8 -0
  109. package/src/generated/api/Events.ts +2 -0
  110. package/src/generated/api/InstanceAddToCollection.ts +14 -0
  111. package/src/generated/api/InstanceCreate.ts +32 -0
  112. package/src/generated/api/InstanceCreated.ts +16 -0
  113. package/src/generated/api/InstanceError.ts +10 -0
  114. package/src/generated/api/InstanceRemove.ts +11 -0
  115. package/src/generated/api/InstanceRemoveFromCollection.ts +14 -0
  116. package/src/generated/api/InstanceRemoved.ts +9 -0
  117. package/src/generated/api/InstanceUpdate.ts +14 -0
  118. package/src/generated/api/InstanceUpdated.ts +3 -0
  119. package/src/generated/api/KeyClass.ts +6 -0
  120. package/src/generated/api/LogTail.ts +6 -0
  121. package/src/generated/api/LogTailParams.ts +10 -0
  122. package/src/generated/api/PerspectiveInstanceAddToCollectionParams.ts +11 -0
  123. package/src/generated/api/PerspectiveInstanceCreateParams.ts +29 -0
  124. package/src/generated/api/PerspectiveInstanceRemoveFromCollectionParams.ts +11 -0
  125. package/src/generated/api/PerspectiveInstanceRemoveParams.ts +7 -0
  126. package/src/generated/api/PerspectiveInstanceUpdateParams.ts +11 -0
  127. package/src/generated/api/Pinned.ts +7 -0
  128. package/src/generated/api/ReadOnlyReason.ts +6 -0
  129. package/src/generated/api/RefusalReason.ts +6 -0
  130. package/src/generated/api/RpcMethods.ts +30 -0
  131. package/src/generated/api/RuntimeConfig.ts +24 -0
  132. package/src/generated/api/SetConfigParams.ts +6 -0
  133. package/src/generated/api/SetConfigResult.ts +7 -0
  134. package/src/generated/api/ValidationError.ts +34 -0
  135. package/src/generated/api/ValidationProblem.ts +7 -0
  136. package/src/generated/api/WriteStep.ts +6 -0
  137. package/src/generated/api/index.ts +34 -0
  138. package/src/identity/IdentityClient.ts +20 -0
  139. package/src/model/shacl-gen.ts +4 -2
  140. package/src/neighbourhood/MeshManager.test.ts +57 -0
  141. package/src/neighbourhood/MeshManager.ts +26 -0
  142. package/src/neighbourhood/NeighbourhoodProxy.ts +7 -2
  143. package/src/neighbourhood/Session.test.ts +355 -3
  144. package/src/neighbourhood/Session.ts +170 -28
  145. package/src/perspectives/PerspectiveClient.ts +56 -0
  146. package/src/perspectives/PerspectiveProxy.test.ts +34 -0
  147. package/src/perspectives/PerspectiveProxy.ts +76 -2
  148. package/src/perspectives/WakerSubscriptionManager.test.ts +379 -1
  149. package/src/perspectives/WakerSubscriptionManager.ts +189 -41
  150. package/src/runtime/RuntimeClient.ts +25 -1
  151. package/src/shacl/SHACLFlow.test.ts +4 -2
  152. package/src/shacl/SHACLShape.test.ts +10 -3
  153. package/src/shacl/SHACLShape.ts +6 -2
package/lib/index.cjs CHANGED
@@ -48,6 +48,7 @@ const READ_METHODS = new Set([
48
48
  "hosting.info",
49
49
  "hosting.wallet",
50
50
  "hosting.walletHistory",
51
+ "identity.custodyStatus",
51
52
  "identity.devices",
52
53
  "identity.joinStatus",
53
54
  "identity.log",
@@ -82,6 +83,7 @@ const READ_METHODS = new Set([
82
83
  "perspective.subjectClassesOf",
83
84
  "perspective.verifyFlowReceipt",
84
85
  "runtime.computeLog",
86
+ "runtime.config",
85
87
  "runtime.freeHostingEnabled",
86
88
  "runtime.friendStatus",
87
89
  "runtime.friends",
@@ -90,6 +92,7 @@ const READ_METHODS = new Set([
90
92
  "runtime.inbox",
91
93
  "runtime.info",
92
94
  "runtime.linkLanguageTemplates",
95
+ "runtime.logTail",
93
96
  "runtime.networkMetrics",
94
97
  "runtime.notifications",
95
98
  "runtime.outbox",
@@ -141,11 +144,12 @@ const OPENS_METHODS = new Set([
141
144
 
142
145
  /** Error thrown by ApiClient when an RPC call fails. */
143
146
  class RpcError extends Error {
144
- constructor(status, body) {
147
+ constructor(status, body, data) {
145
148
  super(`RPC error ${status}: ${body}`);
146
149
  this.name = "RpcError";
147
150
  this.status = status;
148
151
  this.body = body;
152
+ this.data = data;
149
153
  }
150
154
  }
151
155
  const DEFAULT_TIMEOUT_MS = 30000;
@@ -331,7 +335,7 @@ class ApiClient {
331
335
  pending.resolve(parsed.result);
332
336
  return;
333
337
  }
334
- const rpcError = new RpcError(error.code ?? 500, error.message ?? 'Unknown error');
338
+ const rpcError = new RpcError(error.code ?? 500, error.message ?? 'Unknown error', error.data);
335
339
  pending.reject(rpcError);
336
340
  // The executor answers 401 only when the token stopped working, then closes the socket.
337
341
  if (rpcError.status === 401)
@@ -3151,6 +3155,8 @@ function parseCallMessage(payload) {
3151
3155
  }
3152
3156
  if (msg.kind === "reset")
3153
3157
  return { ...envelope, kind: "reset" };
3158
+ if (msg.kind === "beat")
3159
+ return { ...envelope, kind: "beat" };
3154
3160
  if (msg.kind === "data") {
3155
3161
  const { label, data, binary } = msg;
3156
3162
  if (typeof label !== "string" || typeof data !== "string")
@@ -3470,6 +3476,11 @@ class MeshManager {
3470
3476
  const to = payload.to;
3471
3477
  if (typeof to === "string" && to !== TARGET_ALL && to !== this.selfId)
3472
3478
  return;
3479
+ // Liveness, not signalling: reported for any sender, never held.
3480
+ if (message.kind === "beat") {
3481
+ this.emit("beat", from);
3482
+ return;
3483
+ }
3473
3484
  // Only peers the roster placed in the call. Without this, anyone on
3474
3485
  // the channel could open a connection by sending an offer.
3475
3486
  const slot = this.slots.get(from);
@@ -3641,6 +3652,16 @@ class MeshManager {
3641
3652
  sendData(label, data, binary = false) {
3642
3653
  this.publish({ v: CALL_PROTOCOL_VERSION, call: this.callId, to: TARGET_ALL, kind: "data", label, data, binary });
3643
3654
  }
3655
+ /**
3656
+ * Tell every peer of the call that this one is still in it. Through
3657
+ * {@link publish}, so a beat's publish result is counted like any other
3658
+ * send. Nothing once the mesh has left.
3659
+ */
3660
+ beat() {
3661
+ if (this.closed)
3662
+ return;
3663
+ this.publish({ v: CALL_PROTOCOL_VERSION, call: this.callId, to: TARGET_ALL, kind: "beat" });
3664
+ }
3644
3665
  subscribeDataChannel(callback) {
3645
3666
  this.dataListeners.add(callback);
3646
3667
  return () => this.dataListeners.delete(callback);
@@ -4266,24 +4287,62 @@ class MeshManager {
4266
4287
  * online-status link with this predicate, its mesh peer id as source and
4267
4288
  * the room id as target. Other agents polling `onlineAgents()` use this
4268
4289
  * to discover the roster without a join message; one agent's devices each
4269
- * add a link of their own to the agent's one status.
4290
+ * add a link of their own to the agent's one status, with the marker
4291
+ * ({@link CALL_BEATS_PREDICATE}) beside it.
4270
4292
  */
4271
4293
  const CALL_PRESENCE_PREDICATE = "ad4m://session/in-call";
4272
- /** How often (ms) the mesh session polls `onlineAgents` for roster changes. */
4273
- const ROSTER_POLL_INTERVAL_MS = 3000;
4274
4294
  /**
4275
- * The mesh peer a call-presence link of `did` announces, or `null`. A link
4276
- * counts only for a peer of the agent whose status carries it, so no agent
4277
- * can place another in a call.
4295
+ * Marker predicate: the device beats. Beside its presence link, each device
4296
+ * in a mesh call writes one link with this predicate, its peer id as source
4297
+ * and the room id as target, once, at join. The marker never changes; the
4298
+ * beat itself travels as a `beat` message over the call's signalling
4299
+ * ({@link MeshManager.beat}), every {@link BEAT_INTERVAL_MS}, and is never
4300
+ * persisted. A reader leaves out a device with the marker that it has not
4301
+ * heard beat for {@link PRESENCE_STALE_MS} by its own clock, counted from
4302
+ * when it first saw the device if it never heard it. A presence link without
4303
+ * the marker (an SDK from before the beat) never goes stale.
4278
4304
  */
4279
- function presencePeer(did, link, roomId) {
4280
- if (link?.predicate !== CALL_PRESENCE_PREDICATE || link.target !== roomId)
4281
- return null;
4282
- const source = link.source;
4305
+ const CALL_BEATS_PREDICATE = "ad4m://session/in-call-beat";
4306
+ /**
4307
+ * How often (ms) a mesh device beats. Beats are best effort: a reader keeps a
4308
+ * device through three lost beats in a row, with 10 s to spare for the fourth.
4309
+ */
4310
+ const BEAT_INTERVAL_MS = 20000;
4311
+ /** How long (ms) a reader keeps a device with the marker that it has not heard beat. */
4312
+ const PRESENCE_STALE_MS = 90000;
4313
+ /** How often (ms) the mesh session polls `onlineAgents` for roster changes. */
4314
+ const ROSTER_POLL_INTERVAL_MS = 3000;
4315
+ /** `source` when it names a device of `did`, else `null`: no agent can speak for another's devices. */
4316
+ function peerOf(did, source) {
4283
4317
  if (typeof source !== "string" || source === did || agentOfMeshPeer(source) !== did)
4284
4318
  return null;
4285
4319
  return source;
4286
4320
  }
4321
+ /**
4322
+ * The mesh peer a call-presence link or marker of `did` names for `roomId`,
4323
+ * or `null`. A link counts only for a peer of the agent whose status carries
4324
+ * it, so no agent can place another in a call.
4325
+ */
4326
+ function callPeer(did, link, roomId, predicate) {
4327
+ if (link?.predicate !== predicate || link.target !== roomId)
4328
+ return null;
4329
+ return peerOf(did, link.source);
4330
+ }
4331
+ /** The devices of `did` its status links put in `roomId`, each with whether it carries the marker. */
4332
+ function roomPeers(did, links, roomId) {
4333
+ const peers = new Map();
4334
+ for (const link of links) {
4335
+ const peer = callPeer(did, link, roomId, CALL_PRESENCE_PREDICATE);
4336
+ if (peer)
4337
+ peers.set(peer, false);
4338
+ }
4339
+ for (const link of links) {
4340
+ const peer = callPeer(did, link, roomId, CALL_BEATS_PREDICATE);
4341
+ if (peer && peers.has(peer))
4342
+ peers.set(peer, true);
4343
+ }
4344
+ return peers;
4345
+ }
4287
4346
  /**
4288
4347
  * Where a mesh session hears that this device joined the same call again,
4289
4348
  * from another tab. `BroadcastChannel` reaches every tab of one browser
@@ -4368,23 +4427,59 @@ function createSession(config) {
4368
4427
  * leaving restores if the status cannot be read then. */
4369
4428
  let statusBeforeCall = [];
4370
4429
  let announced = false;
4371
- /** This agent's status links, without this device's presence link for this call. */
4372
- async function ownLinksWithoutCall() {
4373
- const status = ownOnlineStatus ? await ownOnlineStatus() : null;
4430
+ let beatInterval = null;
4431
+ /**
4432
+ * Per device the roster poll found with the marker: when this session last
4433
+ * heard it beat or found its pair connected, or, until then, when the poll first saw it (its own
4434
+ * clock). Pruned to the devices the last poll saw.
4435
+ */
4436
+ const heardAt = new Map();
4437
+ /** A repair of this agent's status in flight: a withdraw waits for it, so it cannot land after the withdraw. */
4438
+ let repairing = null;
4439
+ /** When the last repair started: a failed one is tried again only after {@link PRESENCE_STALE_MS}. */
4440
+ let repairedAt = -Infinity;
4441
+ /**
4442
+ * Whether `peer`, carrying the marker, has not beaten for {@link PRESENCE_STALE_MS}.
4443
+ * A pair connected now counts as heard: media flowing proves the peer
4444
+ * alive while its beats, signals sent without delivery, may be lost.
4445
+ */
4446
+ function isStale(peer, now, states) {
4447
+ if (!heardAt.has(peer) || states.get(peer) === "connected")
4448
+ heardAt.set(peer, now);
4449
+ return now - heardAt.get(peer) >= PRESENCE_STALE_MS;
4450
+ }
4451
+ /**
4452
+ * `status`'s links without the presence links and markers of the devices
4453
+ * in `drop`, and without a marker whose device has no presence link.
4454
+ */
4455
+ function linksWithout(status, drop) {
4456
+ const all = (status?.data?.links ?? []).map((link) => link.data);
4457
+ const peers = roomPeers(agentDid, all, roomId);
4374
4458
  const links = [];
4375
- for (const link of status?.data?.links ?? []) {
4376
- const l = link.data;
4459
+ for (const l of all) {
4377
4460
  if (!l?.source || l.target === undefined)
4378
4461
  continue;
4379
- if (presencePeer(agentDid, l, roomId) === selfPeer)
4462
+ const peer = callPeer(agentDid, l, roomId, CALL_PRESENCE_PREDICATE) ?? callPeer(agentDid, l, roomId, CALL_BEATS_PREDICATE);
4463
+ if (peer && (drop.has(peer) || !peers.has(peer)))
4380
4464
  continue;
4381
4465
  links.push({ source: l.source, target: l.target, ...(l.predicate ? { predicate: l.predicate } : {}) });
4382
4466
  }
4383
4467
  return links;
4384
4468
  }
4469
+ /** This agent's status links without this device's call links. */
4470
+ async function ownLinksWithoutCall() {
4471
+ return linksWithout(ownOnlineStatus ? await ownOnlineStatus() : null, new Set([selfPeer]));
4472
+ }
4473
+ /** This device's presence link and marker for this call. */
4474
+ function callLinks() {
4475
+ return [
4476
+ { source: selfPeer, predicate: CALL_PRESENCE_PREDICATE, target: roomId },
4477
+ { source: selfPeer, predicate: CALL_BEATS_PREDICATE, target: roomId },
4478
+ ];
4479
+ }
4385
4480
  /**
4386
- * Add this call's presence link to the agent's online status. Other
4387
- * agents' roster polls pick it up.
4481
+ * Add this call's presence link and marker to the agent's online status.
4482
+ * Other agents' roster polls pick it up.
4388
4483
  */
4389
4484
  async function announceCallPresence() {
4390
4485
  if (!setOnlineStatus)
@@ -4394,19 +4489,47 @@ function createSession(config) {
4394
4489
  console.warn("session: reading own status failed:", err);
4395
4490
  return [];
4396
4491
  });
4397
- const presence = { source: selfPeer, predicate: CALL_PRESENCE_PREDICATE, target: roomId };
4398
- await setOnlineStatus({ links: [...statusBeforeCall, presence] });
4492
+ await setOnlineStatus({ links: [...statusBeforeCall, ...callLinks()] });
4399
4493
  announced = true;
4400
4494
  }
4401
4495
  catch (err) {
4402
4496
  console.warn("session: call-presence announcement failed:", err);
4403
4497
  }
4404
4498
  }
4405
- /** Take this call's presence link out of the agent's status again. */
4499
+ /**
4500
+ * The one status write a poll may make: take out the links of this agent's
4501
+ * devices in `stale`, and put this device's back if they are missing (a
4502
+ * device of this agent that stopped hearing this one took them out). `own`
4503
+ * is the status the poll read; an unread or unset one is never written over.
4504
+ * At most one write per {@link PRESENCE_STALE_MS}, so a write that fails, or
4505
+ * a sibling that keeps taking this device out, cannot write on every poll.
4506
+ */
4507
+ function repairOwnStatus(own, stale) {
4508
+ const links = own?.data?.links;
4509
+ if (!setOnlineStatus || !announced || repairing || !links)
4510
+ return;
4511
+ // Listed means the presence link and the marker: without the marker,
4512
+ // readers would never find this device stale.
4513
+ const listed = roomPeers(agentDid, links.map((l) => l.data), roomId).get(selfPeer) === true;
4514
+ if (stale.size === 0 && listed)
4515
+ return;
4516
+ const now = Date.now();
4517
+ if (now - repairedAt < PRESENCE_STALE_MS)
4518
+ return;
4519
+ repairedAt = now;
4520
+ const write = setOnlineStatus({ links: [...linksWithout(own, new Set([...stale, selfPeer])), ...callLinks()] })
4521
+ .catch((err) => console.warn("session: repairing call presence failed:", err))
4522
+ .finally(() => { if (repairing === write)
4523
+ repairing = null; });
4524
+ repairing = write;
4525
+ }
4526
+ /** Take this call's presence link and marker out of the agent's status again. */
4406
4527
  async function withdrawCallPresence() {
4407
4528
  if (!setOnlineStatus || !announced)
4408
4529
  return;
4409
4530
  announced = false;
4531
+ if (repairing)
4532
+ await repairing;
4410
4533
  try {
4411
4534
  const links = await ownLinksWithoutCall().catch((err) => {
4412
4535
  console.warn("session: reading own status failed:", err);
@@ -4428,6 +4551,12 @@ function createSession(config) {
4428
4551
  * from `ownOnlineStatus`, and passes the peers to `mesh.setRoster()`.
4429
4552
  * That function opens connections to new arrivals and tears down
4430
4553
  * connections to departed peers.
4554
+ *
4555
+ * A device that died without leaving keeps its link while its agent's
4556
+ * other devices keep the status, so the poll leaves out a device with the
4557
+ * marker ({@link CALL_BEATS_PREDICATE}) that has not beaten for
4558
+ * {@link PRESENCE_STALE_MS}, and takes such devices of this agent out of
4559
+ * its status ({@link repairOwnStatus}).
4431
4560
  */
4432
4561
  async function pollRoster() {
4433
4562
  const mesh = meshManager;
@@ -4440,12 +4569,24 @@ function createSession(config) {
4440
4569
  // The session left while the poll was in flight.
4441
4570
  if (meshManager !== mesh)
4442
4571
  return;
4572
+ const now = Date.now();
4573
+ const states = mesh.peerStates();
4443
4574
  const inCall = new Set();
4575
+ const seen = new Set();
4576
+ const staleOwn = new Set();
4444
4577
  const collect = (did, links) => {
4445
- for (const link of links ?? []) {
4446
- const peer = presencePeer(did, link.data, roomId);
4447
- if (peer && peer !== selfPeer)
4578
+ for (const [peer, beats] of roomPeers(did, (links ?? []).map((l) => l.data), roomId)) {
4579
+ if (peer === selfPeer)
4580
+ continue;
4581
+ if (!beats) {
4582
+ inCall.add(peer);
4583
+ continue;
4584
+ }
4585
+ seen.add(peer);
4586
+ if (!isStale(peer, now, states))
4448
4587
  inCall.add(peer);
4588
+ else if (did === agentDid)
4589
+ staleOwn.add(peer);
4449
4590
  }
4450
4591
  };
4451
4592
  // Each agent's status is a signed perspective: its links sit
@@ -4457,7 +4598,11 @@ function createSession(config) {
4457
4598
  collect(agent.did, agent.status?.data?.links);
4458
4599
  }
4459
4600
  collect(agentDid, own?.data?.links);
4601
+ for (const peer of [...heardAt.keys()])
4602
+ if (!seen.has(peer))
4603
+ heardAt.delete(peer);
4460
4604
  mesh.setRoster([...inCall]);
4605
+ repairOwnStatus(own, staleOwn);
4461
4606
  }
4462
4607
  catch (err) {
4463
4608
  console.warn("session: roster poll failed:", err);
@@ -4466,16 +4611,37 @@ function createSession(config) {
4466
4611
  polling = false;
4467
4612
  }
4468
4613
  }
4469
- function startRosterPolling() {
4614
+ /**
4615
+ * Start the roster poll and this device's beat. Each runs on its own
4616
+ * timer: a poll that hangs on a slow `onlineAgents` must not stop the beat
4617
+ * while media still flows.
4618
+ */
4619
+ function startRosterPolling(mesh) {
4620
+ heardAt.clear();
4621
+ repairedAt = -Infinity;
4622
+ // `peer` is the verified author's DID with the device its payload names:
4623
+ // a beat can only vouch for its own agent's devices. Only devices the
4624
+ // poll tracks are recorded, so a stranger's beats cannot grow the map.
4625
+ mesh.on("beat", (peer) => {
4626
+ if (meshManager === mesh && heardAt.has(peer))
4627
+ heardAt.set(peer, Date.now());
4628
+ });
4629
+ mesh.beat();
4630
+ beatInterval = setInterval(() => mesh.beat(), BEAT_INTERVAL_MS);
4470
4631
  // Immediate first poll, then periodic
4471
4632
  void pollRoster();
4472
4633
  rosterInterval = setInterval(() => void pollRoster(), ROSTER_POLL_INTERVAL_MS);
4473
4634
  }
4635
+ /** Stop the roster poll and the beat. Beats are never persisted: nothing else to undo. */
4474
4636
  function stopRosterPolling() {
4475
4637
  if (rosterInterval !== null) {
4476
4638
  clearInterval(rosterInterval);
4477
4639
  rosterInterval = null;
4478
4640
  }
4641
+ if (beatInterval !== null) {
4642
+ clearInterval(beatInterval);
4643
+ beatInterval = null;
4644
+ }
4479
4645
  }
4480
4646
  // ── Mesh wiring helpers ─────────────────────────────────────────
4481
4647
  function wireMeshEvents(mesh) {
@@ -4648,7 +4814,7 @@ function createSession(config) {
4648
4814
  await withdrawCallPresence();
4649
4815
  throw new Error("Session destroyed");
4650
4816
  }
4651
- startRosterPolling();
4817
+ startRosterPolling(mesh);
4652
4818
  emit("topology-changed", "mesh");
4653
4819
  setState("active");
4654
4820
  return;
@@ -4880,11 +5046,16 @@ class NeighbourhoodProxy {
4880
5046
  async sendSignalU(remoteAgentDid, payload) {
4881
5047
  return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sendSignalU(__classPrivateFieldGet$a(this, _NeighbourhoodProxy_pID, "f"), remoteAgentDid, payload);
4882
5048
  }
4883
- /** Broadcast a signed signal to all agents in the neighbourhood. */
5049
+ /**
5050
+ * Broadcast a signed signal to all agents in the neighbourhood. The
5051
+ * sender's own agent gets it too (its other clients hear it), so a handler
5052
+ * that must not act on its own messages drops them by author or device;
5053
+ * `loopback` adds a second copy for the sender's executor.
5054
+ */
4884
5055
  async sendBroadcast(payload, loopback = false) {
4885
5056
  return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sendBroadcast(__classPrivateFieldGet$a(this, _NeighbourhoodProxy_pID, "f"), payload, loopback);
4886
5057
  }
4887
- /** Broadcast an unsigned signal to all agents in the neighbourhood. */
5058
+ /** Broadcast an unsigned signal to all agents in the neighbourhood; delivered as {@link sendBroadcast}. */
4888
5059
  async sendBroadcastU(payload, loopback = false) {
4889
5060
  return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sendBroadcastU(__classPrivateFieldGet$a(this, _NeighbourhoodProxy_pID, "f"), payload, loopback);
4890
5061
  }
@@ -5593,7 +5764,10 @@ class SHACLShape {
5593
5764
  const statements = (source) => links
5594
5765
  .filter(l => l.source === source && l.predicate !== 'sh://property')
5595
5766
  .flatMap(l => l.predicate === 'sh://in'
5596
- ? [`sh:in ( ${JSON.parse(l.target.slice(15)).map((v) => str(v.value)).join(' ')} )`, `ad4m:in ${obj(l)}`]
5767
+ ? [`sh:in ( ${JSON.parse(l.target.slice(15)).map((v) => {
5768
+ const value = v !== null && typeof v === 'object' && 'value' in v ? v.value : v;
5769
+ return typeof value === 'string' ? str(value) : JSON.stringify(value);
5770
+ }).join(' ')} )`, `ad4m:in ${obj(l)}`]
5597
5771
  : [`${pred(l.predicate)} ${obj(l)}`]);
5598
5772
  const properties = links
5599
5773
  .filter(l => l.source === this.nodeShapeUri && l.predicate === 'sh://property')
@@ -5832,7 +6006,8 @@ class SHACLShape {
5832
6006
  target: prop.class
5833
6007
  });
5834
6008
  }
5835
- if (prop.in && prop.in.length > 0) {
6009
+ // `in: []` is a deny-all constraint, not the absence of one — store it.
6010
+ if (prop.in !== undefined) {
5836
6011
  links.push({
5837
6012
  source: propShapeId,
5838
6013
  predicate: "sh://in",
@@ -6301,8 +6476,10 @@ isAbstract) {
6301
6476
  if (propMeta.flag && propMeta.initial) {
6302
6477
  propShape.hasValue = propMeta.initial;
6303
6478
  }
6304
- // sh:in — allowed values (enum constraint)
6305
- if (propMeta.options && propMeta.options.length > 0) {
6479
+ // sh:in — allowed values (enum constraint). An explicit empty list
6480
+ // is kept: it denies every value, which dropping would widen to
6481
+ // unconstrained.
6482
+ if (propMeta.options !== undefined) {
6306
6483
  propShape.in = propMeta.options;
6307
6484
  }
6308
6485
  // AD4M-specific metadata
@@ -9461,6 +9638,15 @@ class PerspectiveProxy {
9461
9638
  invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
9462
9639
  return result;
9463
9640
  }
9641
+ /**
9642
+ * Drops an open batch without committing it — the recovery for a failed batched call:
9643
+ * a failed call does not roll back the calls before it and may have staged part of its
9644
+ * own work, so discard rather than commit to keep the successful calls. Resolves `true`
9645
+ * when the batch was open and is now dropped.
9646
+ */
9647
+ async discardBatch(batchId) {
9648
+ return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").discardBatch(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, batchId);
9649
+ }
9464
9650
  /**
9465
9651
  * Retrieves and renders an Expression referenced in this perspective.
9466
9652
  *
@@ -10067,6 +10253,60 @@ class PerspectiveProxy {
10067
10253
  await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").updateSubject(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, className, exprAddr, JSON.stringify(values), batchId);
10068
10254
  invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10069
10255
  }
10256
+ /**
10257
+ * Creates an instance of a subject class, validated by the executor against the class's
10258
+ * SHACL shape before anything is written (each property's type, which are required, which
10259
+ * take a single value, `sh:in`): the same check as the MCP `instance_create` tool. A refused
10260
+ * write rejects with an `RpcError` whose `data` is an `InstanceError` (status 422 and
10261
+ * `kind: 'validation'` for a shape violation, with one `ValidationError` per property) and
10262
+ * stages nothing. With `batchId` a non-validation failure can leave part of the write
10263
+ * staged in the batch — discard it ({@link discardBatch}), don't commit it to keep
10264
+ * earlier calls. An instance created in the same batch is not found — existence reads
10265
+ * committed state only — so a create followed by an update, remove or
10266
+ * `instanceAddToCollection` of the new instance in one batch fails `notFound`; put a new
10267
+ * instance's initial collection items on the create itself.
10268
+ *
10269
+ * @example
10270
+ * const { baseUri } = await perspective.instanceCreate({ className: "Task", properties: { title: "Write" } });
10271
+ */
10272
+ async instanceCreate(body) {
10273
+ const created = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceCreate(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10274
+ invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10275
+ return created;
10276
+ }
10277
+ /** Sets single-valued properties of an instance, validated; the others stay. See {@link instanceCreate}. */
10278
+ async instanceUpdate(body) {
10279
+ const updated = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceUpdate(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10280
+ invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10281
+ return updated;
10282
+ }
10283
+ /** Removes an instance and every link to and from it. See {@link instanceCreate}. */
10284
+ async instanceRemove(body) {
10285
+ // Outside a batch the links go one by one, so a rejection (`partiallyRemoved`) can
10286
+ // come after some are gone: invalidate either way.
10287
+ try {
10288
+ return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceRemove(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10289
+ }
10290
+ finally {
10291
+ invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10292
+ }
10293
+ }
10294
+ /** Adds an item to a collection of an instance, validated. See {@link instanceCreate}. */
10295
+ async instanceAddToCollection(body) {
10296
+ const added = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceAddToCollection(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10297
+ invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10298
+ return added;
10299
+ }
10300
+ /** Removes an item from a collection of an instance. See {@link instanceCreate}. */
10301
+ async instanceRemoveFromCollection(body) {
10302
+ // Like instanceRemove, a rejection can come after some links are gone.
10303
+ try {
10304
+ return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceRemoveFromCollection(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10305
+ }
10306
+ finally {
10307
+ invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10308
+ }
10309
+ }
10070
10310
  async getSubjectData(subjectClass, exprAddr) {
10071
10311
  if (typeof subjectClass === "string") {
10072
10312
  return JSON.parse(await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").getSubjectData(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ className: subjectClass }), exprAddr));
@@ -10564,7 +10804,9 @@ class PerspectiveProxy {
10564
10804
  required: minCount > 0,
10565
10805
  collection: isCollection,
10566
10806
  writable,
10567
- ...(options && options.length > 0 ? { options } : {}),
10807
+ // `options: []` means "allows nothing" — keep it distinct
10808
+ // from an absent constraint.
10809
+ ...(options !== undefined ? { options } : {}),
10568
10810
  };
10569
10811
  });
10570
10812
  return { className: safeName, shapeUri, properties };
@@ -10613,7 +10855,7 @@ class PerspectiveProxy {
10613
10855
  return {};
10614
10856
  const result = {};
10615
10857
  for (const prop of shape.properties) {
10616
- if (prop.options && prop.options.length > 0) {
10858
+ if (prop.options !== undefined) {
10617
10859
  result[prop.name] = prop.options;
10618
10860
  }
10619
10861
  }
@@ -11035,6 +11277,42 @@ class PerspectiveClient {
11035
11277
  async removeSubject(uuid, subjectClass, expressionAddress, batchId) {
11036
11278
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeSubject', { uuid, subjectClass, expressionAddress, batchId });
11037
11279
  }
11280
+ /**
11281
+ * Validated writes (`perspective.instance*`): the executor checks each against the class's
11282
+ * SHACL shape — each property's type, which are required, which take a single value, `sh:in`
11283
+ * — before writing anything. A refused write rejects with an `RpcError` whose `data` is an
11284
+ * `InstanceError` and stages nothing for that call; a shape violation is status 422 with
11285
+ * `data.kind === 'validation'` and `data.errors` naming each property.
11286
+ *
11287
+ * With `batchId` the write is staged into that open batch and lands on its commit; the
11288
+ * link reads a write does (collection membership, the remove cascade) see the batch's own
11289
+ * staged work, but an instance created in the same batch is not found — instance existence
11290
+ * reads committed state only, so a create followed by an update, remove or
11291
+ * `instanceAddToCollection` of the new instance in one batch fails `notFound`; put a new
11292
+ * instance's initial collection items on the create itself. A failure that is not a
11293
+ * refusal — a store error mid-write, `failed` / `partiallyRemoved` — can leave part of the
11294
+ * write staged in the batch: discard it ({@link discardBatch}) instead of committing
11295
+ * it to keep the calls that succeeded.
11296
+ */
11297
+ async instanceCreate(uuid, body) {
11298
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceCreate', { uuid, ...body });
11299
+ }
11300
+ /** Sets the given single-valued properties; the others stay. See {@link instanceCreate}. */
11301
+ async instanceUpdate(uuid, body) {
11302
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceUpdate', { uuid, ...body });
11303
+ }
11304
+ /** Removes the instance and every link to and from it. See {@link instanceCreate}. */
11305
+ async instanceRemove(uuid, body) {
11306
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceRemove', { uuid, ...body });
11307
+ }
11308
+ /** Adds an item to a collection (a no-op when it is a member). See {@link instanceCreate}. */
11309
+ async instanceAddToCollection(uuid, body) {
11310
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceAddToCollection', { uuid, ...body });
11311
+ }
11312
+ /** Removes an item's membership link from a collection. See {@link instanceCreate}. */
11313
+ async instanceRemoveFromCollection(uuid, body) {
11314
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceRemoveFromCollection', { uuid, ...body });
11315
+ }
11038
11316
  async getSubjectData(uuid, subjectClass, expressionAddress) {
11039
11317
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.getSubjectData', { uuid, subjectClass, expressionAddress });
11040
11318
  }
@@ -11096,6 +11374,15 @@ class PerspectiveClient {
11096
11374
  const diff = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.commitBatch', { uuid, batchId });
11097
11375
  return LinkExpressionMutations.fromWire(diff);
11098
11376
  }
11377
+ /**
11378
+ * Drops an open batch without committing it — the recovery for a failed batched call:
11379
+ * a failed call does not roll back the calls before it and may have staged part of its
11380
+ * own work, so discard rather than commit to keep the successful calls. Resolves `true`
11381
+ * when the batch was open and is now dropped.
11382
+ */
11383
+ async discardBatch(uuid, batchId) {
11384
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.discardBatch', { uuid, batchId });
11385
+ }
11099
11386
  /** Register a callback that fires after a successful WebSocket reconnect.
11100
11387
  * Passes through to ApiClient.onReconnect(). Returns an unsubscribe function. */
11101
11388
  onReconnect(callback) {
@@ -11143,9 +11430,29 @@ class RuntimeClient {
11143
11430
  async tlsDomain() {
11144
11431
  return __classPrivateFieldGet$5(this, _RuntimeClient_apiClient, "f").call('runtime.tlsDomain', {});
11145
11432
  }
11433
+ /** Stops the executor (exit 0). Only the operator on the executor's machine. */
11146
11434
  async quit() {
11147
11435
  return __classPrivateFieldGet$5(this, _RuntimeClient_apiClient, "f").call('runtime.quit', {});
11148
11436
  }
11437
+ /** Answers, then the executor exits 75 and its supervisor starts it again. */
11438
+ async restart() {
11439
+ return __classPrivateFieldGet$5(this, _RuntimeClient_apiClient, "f").call('runtime.restart', {});
11440
+ }
11441
+ /** The newest lines (at most 2000) of the executor's log file (`--log-dir`). */
11442
+ async logTail(lines) {
11443
+ return __classPrivateFieldGet$5(this, _RuntimeClient_apiClient, "f").call('runtime.logTail', { lines });
11444
+ }
11445
+ /** The executor's config file: its values, every key with its class, and whether a write waits for a restart. */
11446
+ async config() {
11447
+ return __classPrivateFieldGet$5(this, _RuntimeClient_apiClient, "f").call('runtime.config', {});
11448
+ }
11449
+ /**
11450
+ * Writes keys to the executor's config file (`--config`); they take effect at the next
11451
+ * start. A `machine` key from a caller off the executor's machine is refused `local-only`.
11452
+ */
11453
+ async setConfig(set, unset) {
11454
+ return __classPrivateFieldGet$5(this, _RuntimeClient_apiClient, "f").call('runtime.setConfig', { set, unset });
11455
+ }
11149
11456
  async openLink(url) {
11150
11457
  return __classPrivateFieldGet$5(this, _RuntimeClient_apiClient, "f").call('runtime.openLink', { url });
11151
11458
  }
@@ -18939,6 +19246,23 @@ class IdentityClient {
18939
19246
  async devices() {
18940
19247
  return __classPrivateFieldGet$2(this, _IdentityClient_apiClient, "f").call("identity.devices", {});
18941
19248
  }
19249
+ /**
19250
+ * A new main wallet key for this executor, so a revoked executor can link again. The old
19251
+ * key stays for history. Only the operator on the executor's machine (the admin credential
19252
+ * on a loopback listener). A caller without the admin credential gets 403 "Admin credential
19253
+ * required"; the admin credential on a network listener gets 403 `local-only`.
19254
+ */
19255
+ async rekey() {
19256
+ return __classPrivateFieldGet$2(this, _IdentityClient_apiClient, "f").call("identity.rekey", {});
19257
+ }
19258
+ /**
19259
+ * The custody channel: the main agent's device keys (public keys only), the keys a master
19260
+ * key sent to this computer is sealed to. Only the admin credential on a loopback listener
19261
+ * of an executor started with `--custody-channel`; any other caller gets 403.
19262
+ */
19263
+ async custodyStatus() {
19264
+ return __classPrivateFieldGet$2(this, _IdentityClient_apiClient, "f").call("identity.custodyStatus", {});
19265
+ }
18942
19266
  }
18943
19267
  _IdentityClient_apiClient = new WeakMap();
18944
19268
 
@@ -24735,6 +25059,14 @@ class WakerSubscriptionManager {
24735
25059
  * keeps persisting them so a restart restores them (#1595).
24736
25060
  */
24737
25061
  this.reopening = new Map();
25062
+ /**
25063
+ * Mention subscriptions listening through their mention query only, because
25064
+ * their text query failed to open (#1735: a TextContent `contains` scan over a
25065
+ * large neighbourhood can take longer than the handshake budget). The text
25066
+ * query alone is re-attempted: `timer` is the wait before the next attempt,
25067
+ * `proxy` the attempt in flight. `release()` cancels both.
25068
+ */
25069
+ this.textRetries = new Map();
24738
25070
  /**
24739
25071
  * Cancellation tokens for in-flight `subscribe()` calls.
24740
25072
  *
@@ -24793,6 +25125,15 @@ class WakerSubscriptionManager {
24793
25125
  * If a subscription with the same id already exists, it is disposed first.
24794
25126
  */
24795
25127
  async subscribe(sub) {
25128
+ // The manager's own copy: it records `textHistoryRead` on it. A re-derived
25129
+ // subscription under the same id keeps what the manager knows of its text
25130
+ // query.
25131
+ const prior = this.activeSubscriptions.get(sub.id) ??
25132
+ this.pendingSubscriptions.get(sub.id) ??
25133
+ this.reopening.get(sub.id)?.sub;
25134
+ sub = { ...sub };
25135
+ if (prior?.textHistoryRead && sub.textHistoryRead === undefined)
25136
+ sub.textHistoryRead = true;
24796
25137
  // Dispose existing subscription with same id if any. Not `dispose()`: a
24797
25138
  // re-attempt must not start the backoff over.
24798
25139
  this.release(sub.id, false);
@@ -24814,12 +25155,15 @@ class WakerSubscriptionManager {
24814
25155
  if (sub.mentionQuery) {
24815
25156
  this.logger.info(`[waker] ${sub.id}: model query over ${sub.mentionClass}:\n${sub.mentionQuery}`);
24816
25157
  }
24817
- const proxy = sub.className
25158
+ const textProxy = () => sub.className
24818
25159
  ? new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient, sub.className)
24819
25160
  : new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
25161
+ const proxy = textProxy();
24820
25162
  const mentionProxy = sub.mentionQuery
24821
25163
  ? new QuerySubscriptionProxy(sub.perspective, sub.mentionQuery, this.perspectiveClient, sub.mentionClass)
24822
25164
  : undefined;
25165
+ // The live proxies. A text query that failed while the mention query opened
25166
+ // leaves it, and joins it again once a re-attempt opens (#1735).
24823
25167
  const proxies = mentionProxy ? [proxy, mentionProxy] : [proxy];
24824
25168
  // `cancelOpening`: a handshake given up on must not keep the executor
24825
25169
  // computing a first result nobody reads; abandoned ones piled up into
@@ -24832,28 +25176,49 @@ class WakerSubscriptionManager {
24832
25176
  catch { }
24833
25177
  }
24834
25178
  };
24835
- // Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
24836
- // rejects this promise internally when subscribe() fails, and if nobody catches
24837
- // it before the next microtask it crashes the process.
24838
- for (const p of proxies) {
24839
- if (p.initialized && typeof p.initialized.catch === "function")
24840
- p.initialized.catch(() => { });
24841
- }
24842
- // One deadline for the whole handshake: `proxy.subscribe()` and the
25179
+ // One deadline per query's handshake: `proxy.subscribe()` and the
24843
25180
  // `initialized` promise it resolves share the budget, so a hang in either
24844
25181
  // surfaces as the same loud-but-recoverable failure a rejection does.
24845
- const budgetMs = this.subscribeTimeoutMs;
24846
- const startedAt = Date.now();
24847
- const bounded = (step, what) => budgetMs > 0
24848
- ? withTimeout(step, Math.max(0, budgetMs - (Date.now() - startedAt)), `${what} timed out after ${budgetMs}ms`)
24849
- : step;
24850
- try {
24851
- await bounded(Promise.all(proxies.map((p) => p.subscribe())), "subscribe handshake");
24852
- if (this.isStale(sub.id, token)) {
24853
- disposeProxies();
25182
+ const open = async (p, budgetMs) => {
25183
+ // Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
25184
+ // rejects this promise internally when subscribe() fails, and if nobody catches
25185
+ // it before the next microtask it crashes the process.
25186
+ if (p.initialized && typeof p.initialized.catch === "function")
25187
+ p.initialized.catch(() => { });
25188
+ const startedAt = Date.now();
25189
+ const bounded = (step, what) => budgetMs > 0
25190
+ ? withTimeout(step, Math.max(0, budgetMs - (Date.now() - startedAt)), `${what} timed out after ${budgetMs}ms`)
25191
+ : step;
25192
+ await bounded(p.subscribe(), "subscribe handshake");
25193
+ // Stale: the caller disposes the proxies.
25194
+ if (this.isStale(sub.id, token))
24854
25195
  return;
25196
+ await bounded(p.initialized, "subscription initialization");
25197
+ };
25198
+ // A mention subscription's two queries open independently: on a large
25199
+ // neighbourhood the text query (a `contains` scan over every TextContent)
25200
+ // can take longer than the budget while the mention query answers in under
25201
+ // a second (#1735). Waiting on both made the whole subscription fail, and
25202
+ // the agent got no wake at all, not even through a mention link. The
25203
+ // mention query decides; a text query that fails is re-attempted on its own
25204
+ // once the subscription listens.
25205
+ const openings = proxies.map((p) => open(p, this.subscribeTimeoutMs));
25206
+ for (const o of openings)
25207
+ o.catch(() => { });
25208
+ let textFailure;
25209
+ try {
25210
+ await openings[openings.length - 1];
25211
+ if (mentionProxy) {
25212
+ const [text] = await Promise.allSettled([openings[0]]);
25213
+ if (text.status === "rejected") {
25214
+ textFailure = text.reason?.message ?? String(text.reason);
25215
+ try {
25216
+ proxy.dispose({ cancelOpening: true });
25217
+ }
25218
+ catch { }
25219
+ proxies.splice(proxies.indexOf(proxy), 1);
25220
+ }
24855
25221
  }
24856
- await bounded(Promise.all(proxies.map((p) => p.initialized)), "subscription initialization");
24857
25222
  }
24858
25223
  catch (err) {
24859
25224
  const msg = err?.message ?? String(err);
@@ -24898,10 +25263,14 @@ class WakerSubscriptionManager {
24898
25263
  if (seen.size > 0) {
24899
25264
  this.logger.info(`[waker] ${sub.id}: seeded ${seen.size} seen message(s) from persisted state`);
24900
25265
  }
24901
- // `opening` is the result the subscription holds when it opens (`proxy.result`): `onResult`
24902
- // only reports later changes, so this is the one chance to see what was written meanwhile.
24903
25266
  // `of`: the query the result is from, for the log (a mention subscription has two).
24904
- const handleResult = async (result, opening = false, of = "") => {
25267
+ // `opening` marks the result the query holds when it opens (`proxy.result`): `onResult`
25268
+ // only reports later changes, so this is the one chance to see what was written meanwhile.
25269
+ // A mention subscription reads it as `"history"` (recorded as seen, no wake) or `"news"`
25270
+ // (wakes on what is not seen yet: written while the waker was down).
25271
+ const handleResult = async (result, of, opening) => {
25272
+ if (this.isStale(sub.id, token))
25273
+ return;
24905
25274
  this.logger.info(`[waker] ${sub.id}: ${opening ? "opening result" : "onResult fired"}${of} — type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);
24906
25275
  // A model subscription delivers `{ instances }`, SPARQL an array of
24907
25276
  // rows. Anything else (e.g. `false` on a disconnect/reconnect) is
@@ -24936,8 +25305,8 @@ class WakerSubscriptionManager {
24936
25305
  this.logger.info(`[waker] ${sub.id}: no new mention among ${rows.length} items, skipping`);
24937
25306
  return;
24938
25307
  }
24939
- if (opening && !restored) {
24940
- // A new subscription: what it opens on is history, readable on demand, not news.
25308
+ if (opening === "history") {
25309
+ // What it opens on is history, readable on demand, not news.
24941
25310
  this.seenMessages.set(sub.id, currentSeen);
24942
25311
  const done = this.delivered.get(sub.id) ?? new Set();
24943
25312
  for (const address of newMessages)
@@ -24957,6 +25326,10 @@ class WakerSubscriptionManager {
24957
25326
  (ancestors.length ? `; ancestors: ${ancestors.join(", ")}` : ""));
24958
25327
  mentions.push({ address: msgAddr, parents, ancestors, ...provenance.get(msgAddr) });
24959
25328
  }
25329
+ // Released, or replaced under the same id, during the lookups: the state under `sub.id`
25330
+ // is no longer this subscription's, so write nothing and wake for nothing.
25331
+ if (this.isStale(sub.id, token))
25332
+ return;
24960
25333
  this.seenMessages.set(sub.id, currentSeen);
24961
25334
  const pending = this.undelivered.get(sub.id) ?? new Map();
24962
25335
  for (const mention of mentions)
@@ -24980,29 +25353,119 @@ class WakerSubscriptionManager {
24980
25353
  }, this.debounceMs));
24981
25354
  }
24982
25355
  };
24983
- proxy.onResult((result) => handleResult(result));
24984
- mentionProxy?.onResult((result) => handleResult(result, false, " (mention query)"));
24985
- for (const p of proxies) {
25356
+ // Read `p`'s opening result. The mention query's is news only after a restart. The text
25357
+ // query's is news only after a restart and once a text query of this subscription has read
25358
+ // its history (`textHistoryRead`): it may have listened without it, so the seen set may not
25359
+ // hold what the text query finds (#1735).
25360
+ const readOpening = async (p, of) => {
25361
+ if (p.result === undefined)
25362
+ return;
25363
+ const isText = p !== mentionProxy;
25364
+ const news = restored && (!isText || sub.type !== "mention" || sub.textHistoryRead === true);
25365
+ try {
25366
+ await handleResult(p.result, of, news ? "news" : "history");
25367
+ }
25368
+ catch (e) {
25369
+ this.logger.warn(`[waker] ${sub.id}: reading the opening result failed: ${e?.message ?? e}`);
25370
+ }
25371
+ const rows = sub.className ? p.result?.instances : p.result;
25372
+ if (isText && sub.type === "mention" && Array.isArray(rows) && !this.isStale(sub.id, token)) {
25373
+ sub.textHistoryRead = true;
25374
+ }
25375
+ };
25376
+ const listen = (p, of) => {
25377
+ p.onResult((result) => handleResult(result, of));
24986
25378
  p.onStatus?.((status) => this.onReopenStatus(sub, proxies, p, status));
24987
- }
25379
+ };
25380
+ if (proxies.includes(proxy))
25381
+ listen(proxy, "");
25382
+ if (mentionProxy)
25383
+ listen(mentionProxy, " (mention query)");
24988
25384
  if (this.isStale(sub.id, token)) {
24989
25385
  disposeProxies();
24990
25386
  return;
24991
25387
  }
24992
25388
  this.proxies.set(sub.id, proxies);
24993
25389
  this.activeSubscriptions.set(sub.id, sub);
25390
+ if (textFailure !== undefined) {
25391
+ // Re-attempt the text query alone, not the subscription: subscribing it
25392
+ // again would re-seed its seen set from the persisted one, and wake again
25393
+ // on mentions delivered since. Each failed attempt doubles the wait, up to
25394
+ // `maxRetryPendingMs`, between half and all of it, as `scheduleRetry` does.
25395
+ // The handshake budget doubles per failed attempt too: a scan that takes
25396
+ // longer than `subscribeTimeoutMs` (#1735 measured over 30 s) would
25397
+ // otherwise time out on every attempt. It is capped at `maxRetryPendingMs`
25398
+ // (or the first budget, if longer): with one attempt in flight at a time,
25399
+ // the executor then spends at most about as long on an attempt as the
25400
+ // waker waits between two.
25401
+ let ceiling = this.retryPendingMs;
25402
+ let budgetMs = this.subscribeTimeoutMs;
25403
+ const retryText = () => {
25404
+ const delayMs = ceiling / 2 + Math.random() * (ceiling / 2);
25405
+ ceiling = Math.min(ceiling * 2, this.maxRetryPendingMs);
25406
+ const attemptBudgetMs = budgetMs;
25407
+ budgetMs = Math.min(budgetMs * 2, Math.max(this.subscribeTimeoutMs, this.maxRetryPendingMs));
25408
+ const timer = setTimeout(async () => {
25409
+ if (this.textRetries.get(sub.id)?.timer !== timer || this.isStale(sub.id, token))
25410
+ return;
25411
+ const p = textProxy();
25412
+ this.textRetries.set(sub.id, { timer: null, proxy: p });
25413
+ // `release()` disposed it already when the entry no longer holds it.
25414
+ const ours = () => this.textRetries.get(sub.id)?.proxy === p;
25415
+ try {
25416
+ await open(p, attemptBudgetMs);
25417
+ }
25418
+ catch (err) {
25419
+ if (!ours())
25420
+ return;
25421
+ try {
25422
+ p.dispose({ cancelOpening: true });
25423
+ }
25424
+ catch { }
25425
+ if (this.isStale(sub.id, token)) {
25426
+ this.textRetries.delete(sub.id);
25427
+ return;
25428
+ }
25429
+ const nextMs = retryText();
25430
+ this.logger.debug(`[waker] ${sub.id}: text query failed again (${err?.message ?? err}); re-attempting in ${Math.round(nextMs / 1000)}s`);
25431
+ return;
25432
+ }
25433
+ if (!ours())
25434
+ return;
25435
+ this.textRetries.delete(sub.id);
25436
+ if (this.isStale(sub.id, token) || this.proxies.get(sub.id) !== proxies) {
25437
+ try {
25438
+ p.dispose({ cancelOpening: true });
25439
+ }
25440
+ catch { }
25441
+ return;
25442
+ }
25443
+ proxies.push(p);
25444
+ listen(p, "");
25445
+ this.logger.info(`[waker] ${sub.id}: text query opened; listening through both queries`);
25446
+ // The seen set is the mention query's, so a record it already woke on does not wake
25447
+ // again.
25448
+ await readOpening(p, "");
25449
+ if (!this.isStale(sub.id, token))
25450
+ this.persist();
25451
+ }, delayMs);
25452
+ if (typeof timer.unref === "function")
25453
+ timer.unref();
25454
+ this.textRetries.set(sub.id, { timer, proxy: null });
25455
+ return delayMs;
25456
+ };
25457
+ const firstMs = this.retryPendingMs > 0 ? retryText() : undefined;
25458
+ this.logger.warn(`[waker] ${sub.id}: text query failed (${textFailure}); listening through the mention query only, ` +
25459
+ (firstMs === undefined
25460
+ ? "not re-attempting the text query (retryPendingMs is 0)"
25461
+ : `re-attempting the text query in ${Math.round(firstMs / 1000)}s`));
25462
+ }
24994
25463
  // After a restart this wakes on mentions written while the waker was down; on a new
24995
25464
  // subscription it records the existing ones as history. The mention query's first, so a
24996
25465
  // record both hold wakes through its mention link.
24997
25466
  for (const [p, of] of [[mentionProxy, " (mention query)"], [proxy, ""]]) {
24998
- if (p?.result === undefined)
24999
- continue;
25000
- try {
25001
- await handleResult(p.result, true, of);
25002
- }
25003
- catch (e) {
25004
- this.logger.warn(`[waker] ${sub.id}: reading the opening result failed: ${e?.message ?? e}`);
25005
- }
25467
+ if (p && proxies.includes(p))
25468
+ await readOpening(p, of);
25006
25469
  }
25007
25470
  this.persist();
25008
25471
  this.logger.info(`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`);
@@ -25128,6 +25591,18 @@ class WakerSubscriptionManager {
25128
25591
  }
25129
25592
  }
25130
25593
  this.proxies.delete(id);
25594
+ const textRetry = this.textRetries.get(id);
25595
+ if (textRetry) {
25596
+ if (textRetry.timer)
25597
+ clearTimeout(textRetry.timer);
25598
+ try {
25599
+ textRetry.proxy?.dispose({ cancelOpening: true });
25600
+ }
25601
+ catch {
25602
+ /* ignore */
25603
+ }
25604
+ this.textRetries.delete(id);
25605
+ }
25131
25606
  this.reopening.delete(id);
25132
25607
  const timer = this.debounceTimers.get(id);
25133
25608
  if (timer) {