@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
package/lib/index.js CHANGED
@@ -44,6 +44,7 @@ const READ_METHODS = new Set([
44
44
  "hosting.info",
45
45
  "hosting.wallet",
46
46
  "hosting.walletHistory",
47
+ "identity.custodyStatus",
47
48
  "identity.devices",
48
49
  "identity.joinStatus",
49
50
  "identity.log",
@@ -78,6 +79,7 @@ const READ_METHODS = new Set([
78
79
  "perspective.subjectClassesOf",
79
80
  "perspective.verifyFlowReceipt",
80
81
  "runtime.computeLog",
82
+ "runtime.config",
81
83
  "runtime.freeHostingEnabled",
82
84
  "runtime.friendStatus",
83
85
  "runtime.friends",
@@ -86,6 +88,7 @@ const READ_METHODS = new Set([
86
88
  "runtime.inbox",
87
89
  "runtime.info",
88
90
  "runtime.linkLanguageTemplates",
91
+ "runtime.logTail",
89
92
  "runtime.networkMetrics",
90
93
  "runtime.notifications",
91
94
  "runtime.outbox",
@@ -137,11 +140,12 @@ const OPENS_METHODS = new Set([
137
140
 
138
141
  /** Error thrown by ApiClient when an RPC call fails. */
139
142
  class RpcError extends Error {
140
- constructor(status, body) {
143
+ constructor(status, body, data) {
141
144
  super(`RPC error ${status}: ${body}`);
142
145
  this.name = "RpcError";
143
146
  this.status = status;
144
147
  this.body = body;
148
+ this.data = data;
145
149
  }
146
150
  }
147
151
  const DEFAULT_TIMEOUT_MS = 30000;
@@ -327,7 +331,7 @@ class ApiClient {
327
331
  pending.resolve(parsed.result);
328
332
  return;
329
333
  }
330
- const rpcError = new RpcError(error.code ?? 500, error.message ?? 'Unknown error');
334
+ const rpcError = new RpcError(error.code ?? 500, error.message ?? 'Unknown error', error.data);
331
335
  pending.reject(rpcError);
332
336
  // The executor answers 401 only when the token stopped working, then closes the socket.
333
337
  if (rpcError.status === 401)
@@ -3147,6 +3151,8 @@ function parseCallMessage(payload) {
3147
3151
  }
3148
3152
  if (msg.kind === "reset")
3149
3153
  return { ...envelope, kind: "reset" };
3154
+ if (msg.kind === "beat")
3155
+ return { ...envelope, kind: "beat" };
3150
3156
  if (msg.kind === "data") {
3151
3157
  const { label, data, binary } = msg;
3152
3158
  if (typeof label !== "string" || typeof data !== "string")
@@ -3466,6 +3472,11 @@ class MeshManager {
3466
3472
  const to = payload.to;
3467
3473
  if (typeof to === "string" && to !== TARGET_ALL && to !== this.selfId)
3468
3474
  return;
3475
+ // Liveness, not signalling: reported for any sender, never held.
3476
+ if (message.kind === "beat") {
3477
+ this.emit("beat", from);
3478
+ return;
3479
+ }
3469
3480
  // Only peers the roster placed in the call. Without this, anyone on
3470
3481
  // the channel could open a connection by sending an offer.
3471
3482
  const slot = this.slots.get(from);
@@ -3637,6 +3648,16 @@ class MeshManager {
3637
3648
  sendData(label, data, binary = false) {
3638
3649
  this.publish({ v: CALL_PROTOCOL_VERSION, call: this.callId, to: TARGET_ALL, kind: "data", label, data, binary });
3639
3650
  }
3651
+ /**
3652
+ * Tell every peer of the call that this one is still in it. Through
3653
+ * {@link publish}, so a beat's publish result is counted like any other
3654
+ * send. Nothing once the mesh has left.
3655
+ */
3656
+ beat() {
3657
+ if (this.closed)
3658
+ return;
3659
+ this.publish({ v: CALL_PROTOCOL_VERSION, call: this.callId, to: TARGET_ALL, kind: "beat" });
3660
+ }
3640
3661
  subscribeDataChannel(callback) {
3641
3662
  this.dataListeners.add(callback);
3642
3663
  return () => this.dataListeners.delete(callback);
@@ -4262,24 +4283,62 @@ class MeshManager {
4262
4283
  * online-status link with this predicate, its mesh peer id as source and
4263
4284
  * the room id as target. Other agents polling `onlineAgents()` use this
4264
4285
  * to discover the roster without a join message; one agent's devices each
4265
- * add a link of their own to the agent's one status.
4286
+ * add a link of their own to the agent's one status, with the marker
4287
+ * ({@link CALL_BEATS_PREDICATE}) beside it.
4266
4288
  */
4267
4289
  const CALL_PRESENCE_PREDICATE = "ad4m://session/in-call";
4268
- /** How often (ms) the mesh session polls `onlineAgents` for roster changes. */
4269
- const ROSTER_POLL_INTERVAL_MS = 3000;
4270
4290
  /**
4271
- * The mesh peer a call-presence link of `did` announces, or `null`. A link
4272
- * counts only for a peer of the agent whose status carries it, so no agent
4273
- * can place another in a call.
4291
+ * Marker predicate: the device beats. Beside its presence link, each device
4292
+ * in a mesh call writes one link with this predicate, its peer id as source
4293
+ * and the room id as target, once, at join. The marker never changes; the
4294
+ * beat itself travels as a `beat` message over the call's signalling
4295
+ * ({@link MeshManager.beat}), every {@link BEAT_INTERVAL_MS}, and is never
4296
+ * persisted. A reader leaves out a device with the marker that it has not
4297
+ * heard beat for {@link PRESENCE_STALE_MS} by its own clock, counted from
4298
+ * when it first saw the device if it never heard it. A presence link without
4299
+ * the marker (an SDK from before the beat) never goes stale.
4274
4300
  */
4275
- function presencePeer(did, link, roomId) {
4276
- if (link?.predicate !== CALL_PRESENCE_PREDICATE || link.target !== roomId)
4277
- return null;
4278
- const source = link.source;
4301
+ const CALL_BEATS_PREDICATE = "ad4m://session/in-call-beat";
4302
+ /**
4303
+ * How often (ms) a mesh device beats. Beats are best effort: a reader keeps a
4304
+ * device through three lost beats in a row, with 10 s to spare for the fourth.
4305
+ */
4306
+ const BEAT_INTERVAL_MS = 20000;
4307
+ /** How long (ms) a reader keeps a device with the marker that it has not heard beat. */
4308
+ const PRESENCE_STALE_MS = 90000;
4309
+ /** How often (ms) the mesh session polls `onlineAgents` for roster changes. */
4310
+ const ROSTER_POLL_INTERVAL_MS = 3000;
4311
+ /** `source` when it names a device of `did`, else `null`: no agent can speak for another's devices. */
4312
+ function peerOf(did, source) {
4279
4313
  if (typeof source !== "string" || source === did || agentOfMeshPeer(source) !== did)
4280
4314
  return null;
4281
4315
  return source;
4282
4316
  }
4317
+ /**
4318
+ * The mesh peer a call-presence link or marker of `did` names for `roomId`,
4319
+ * or `null`. A link counts only for a peer of the agent whose status carries
4320
+ * it, so no agent can place another in a call.
4321
+ */
4322
+ function callPeer(did, link, roomId, predicate) {
4323
+ if (link?.predicate !== predicate || link.target !== roomId)
4324
+ return null;
4325
+ return peerOf(did, link.source);
4326
+ }
4327
+ /** The devices of `did` its status links put in `roomId`, each with whether it carries the marker. */
4328
+ function roomPeers(did, links, roomId) {
4329
+ const peers = new Map();
4330
+ for (const link of links) {
4331
+ const peer = callPeer(did, link, roomId, CALL_PRESENCE_PREDICATE);
4332
+ if (peer)
4333
+ peers.set(peer, false);
4334
+ }
4335
+ for (const link of links) {
4336
+ const peer = callPeer(did, link, roomId, CALL_BEATS_PREDICATE);
4337
+ if (peer && peers.has(peer))
4338
+ peers.set(peer, true);
4339
+ }
4340
+ return peers;
4341
+ }
4283
4342
  /**
4284
4343
  * Where a mesh session hears that this device joined the same call again,
4285
4344
  * from another tab. `BroadcastChannel` reaches every tab of one browser
@@ -4364,23 +4423,59 @@ function createSession(config) {
4364
4423
  * leaving restores if the status cannot be read then. */
4365
4424
  let statusBeforeCall = [];
4366
4425
  let announced = false;
4367
- /** This agent's status links, without this device's presence link for this call. */
4368
- async function ownLinksWithoutCall() {
4369
- const status = ownOnlineStatus ? await ownOnlineStatus() : null;
4426
+ let beatInterval = null;
4427
+ /**
4428
+ * Per device the roster poll found with the marker: when this session last
4429
+ * heard it beat or found its pair connected, or, until then, when the poll first saw it (its own
4430
+ * clock). Pruned to the devices the last poll saw.
4431
+ */
4432
+ const heardAt = new Map();
4433
+ /** A repair of this agent's status in flight: a withdraw waits for it, so it cannot land after the withdraw. */
4434
+ let repairing = null;
4435
+ /** When the last repair started: a failed one is tried again only after {@link PRESENCE_STALE_MS}. */
4436
+ let repairedAt = -Infinity;
4437
+ /**
4438
+ * Whether `peer`, carrying the marker, has not beaten for {@link PRESENCE_STALE_MS}.
4439
+ * A pair connected now counts as heard: media flowing proves the peer
4440
+ * alive while its beats, signals sent without delivery, may be lost.
4441
+ */
4442
+ function isStale(peer, now, states) {
4443
+ if (!heardAt.has(peer) || states.get(peer) === "connected")
4444
+ heardAt.set(peer, now);
4445
+ return now - heardAt.get(peer) >= PRESENCE_STALE_MS;
4446
+ }
4447
+ /**
4448
+ * `status`'s links without the presence links and markers of the devices
4449
+ * in `drop`, and without a marker whose device has no presence link.
4450
+ */
4451
+ function linksWithout(status, drop) {
4452
+ const all = (status?.data?.links ?? []).map((link) => link.data);
4453
+ const peers = roomPeers(agentDid, all, roomId);
4370
4454
  const links = [];
4371
- for (const link of status?.data?.links ?? []) {
4372
- const l = link.data;
4455
+ for (const l of all) {
4373
4456
  if (!l?.source || l.target === undefined)
4374
4457
  continue;
4375
- if (presencePeer(agentDid, l, roomId) === selfPeer)
4458
+ const peer = callPeer(agentDid, l, roomId, CALL_PRESENCE_PREDICATE) ?? callPeer(agentDid, l, roomId, CALL_BEATS_PREDICATE);
4459
+ if (peer && (drop.has(peer) || !peers.has(peer)))
4376
4460
  continue;
4377
4461
  links.push({ source: l.source, target: l.target, ...(l.predicate ? { predicate: l.predicate } : {}) });
4378
4462
  }
4379
4463
  return links;
4380
4464
  }
4465
+ /** This agent's status links without this device's call links. */
4466
+ async function ownLinksWithoutCall() {
4467
+ return linksWithout(ownOnlineStatus ? await ownOnlineStatus() : null, new Set([selfPeer]));
4468
+ }
4469
+ /** This device's presence link and marker for this call. */
4470
+ function callLinks() {
4471
+ return [
4472
+ { source: selfPeer, predicate: CALL_PRESENCE_PREDICATE, target: roomId },
4473
+ { source: selfPeer, predicate: CALL_BEATS_PREDICATE, target: roomId },
4474
+ ];
4475
+ }
4381
4476
  /**
4382
- * Add this call's presence link to the agent's online status. Other
4383
- * agents' roster polls pick it up.
4477
+ * Add this call's presence link and marker to the agent's online status.
4478
+ * Other agents' roster polls pick it up.
4384
4479
  */
4385
4480
  async function announceCallPresence() {
4386
4481
  if (!setOnlineStatus)
@@ -4390,19 +4485,47 @@ function createSession(config) {
4390
4485
  console.warn("session: reading own status failed:", err);
4391
4486
  return [];
4392
4487
  });
4393
- const presence = { source: selfPeer, predicate: CALL_PRESENCE_PREDICATE, target: roomId };
4394
- await setOnlineStatus({ links: [...statusBeforeCall, presence] });
4488
+ await setOnlineStatus({ links: [...statusBeforeCall, ...callLinks()] });
4395
4489
  announced = true;
4396
4490
  }
4397
4491
  catch (err) {
4398
4492
  console.warn("session: call-presence announcement failed:", err);
4399
4493
  }
4400
4494
  }
4401
- /** Take this call's presence link out of the agent's status again. */
4495
+ /**
4496
+ * The one status write a poll may make: take out the links of this agent's
4497
+ * devices in `stale`, and put this device's back if they are missing (a
4498
+ * device of this agent that stopped hearing this one took them out). `own`
4499
+ * is the status the poll read; an unread or unset one is never written over.
4500
+ * At most one write per {@link PRESENCE_STALE_MS}, so a write that fails, or
4501
+ * a sibling that keeps taking this device out, cannot write on every poll.
4502
+ */
4503
+ function repairOwnStatus(own, stale) {
4504
+ const links = own?.data?.links;
4505
+ if (!setOnlineStatus || !announced || repairing || !links)
4506
+ return;
4507
+ // Listed means the presence link and the marker: without the marker,
4508
+ // readers would never find this device stale.
4509
+ const listed = roomPeers(agentDid, links.map((l) => l.data), roomId).get(selfPeer) === true;
4510
+ if (stale.size === 0 && listed)
4511
+ return;
4512
+ const now = Date.now();
4513
+ if (now - repairedAt < PRESENCE_STALE_MS)
4514
+ return;
4515
+ repairedAt = now;
4516
+ const write = setOnlineStatus({ links: [...linksWithout(own, new Set([...stale, selfPeer])), ...callLinks()] })
4517
+ .catch((err) => console.warn("session: repairing call presence failed:", err))
4518
+ .finally(() => { if (repairing === write)
4519
+ repairing = null; });
4520
+ repairing = write;
4521
+ }
4522
+ /** Take this call's presence link and marker out of the agent's status again. */
4402
4523
  async function withdrawCallPresence() {
4403
4524
  if (!setOnlineStatus || !announced)
4404
4525
  return;
4405
4526
  announced = false;
4527
+ if (repairing)
4528
+ await repairing;
4406
4529
  try {
4407
4530
  const links = await ownLinksWithoutCall().catch((err) => {
4408
4531
  console.warn("session: reading own status failed:", err);
@@ -4424,6 +4547,12 @@ function createSession(config) {
4424
4547
  * from `ownOnlineStatus`, and passes the peers to `mesh.setRoster()`.
4425
4548
  * That function opens connections to new arrivals and tears down
4426
4549
  * connections to departed peers.
4550
+ *
4551
+ * A device that died without leaving keeps its link while its agent's
4552
+ * other devices keep the status, so the poll leaves out a device with the
4553
+ * marker ({@link CALL_BEATS_PREDICATE}) that has not beaten for
4554
+ * {@link PRESENCE_STALE_MS}, and takes such devices of this agent out of
4555
+ * its status ({@link repairOwnStatus}).
4427
4556
  */
4428
4557
  async function pollRoster() {
4429
4558
  const mesh = meshManager;
@@ -4436,12 +4565,24 @@ function createSession(config) {
4436
4565
  // The session left while the poll was in flight.
4437
4566
  if (meshManager !== mesh)
4438
4567
  return;
4568
+ const now = Date.now();
4569
+ const states = mesh.peerStates();
4439
4570
  const inCall = new Set();
4571
+ const seen = new Set();
4572
+ const staleOwn = new Set();
4440
4573
  const collect = (did, links) => {
4441
- for (const link of links ?? []) {
4442
- const peer = presencePeer(did, link.data, roomId);
4443
- if (peer && peer !== selfPeer)
4574
+ for (const [peer, beats] of roomPeers(did, (links ?? []).map((l) => l.data), roomId)) {
4575
+ if (peer === selfPeer)
4576
+ continue;
4577
+ if (!beats) {
4578
+ inCall.add(peer);
4579
+ continue;
4580
+ }
4581
+ seen.add(peer);
4582
+ if (!isStale(peer, now, states))
4444
4583
  inCall.add(peer);
4584
+ else if (did === agentDid)
4585
+ staleOwn.add(peer);
4445
4586
  }
4446
4587
  };
4447
4588
  // Each agent's status is a signed perspective: its links sit
@@ -4453,7 +4594,11 @@ function createSession(config) {
4453
4594
  collect(agent.did, agent.status?.data?.links);
4454
4595
  }
4455
4596
  collect(agentDid, own?.data?.links);
4597
+ for (const peer of [...heardAt.keys()])
4598
+ if (!seen.has(peer))
4599
+ heardAt.delete(peer);
4456
4600
  mesh.setRoster([...inCall]);
4601
+ repairOwnStatus(own, staleOwn);
4457
4602
  }
4458
4603
  catch (err) {
4459
4604
  console.warn("session: roster poll failed:", err);
@@ -4462,16 +4607,37 @@ function createSession(config) {
4462
4607
  polling = false;
4463
4608
  }
4464
4609
  }
4465
- function startRosterPolling() {
4610
+ /**
4611
+ * Start the roster poll and this device's beat. Each runs on its own
4612
+ * timer: a poll that hangs on a slow `onlineAgents` must not stop the beat
4613
+ * while media still flows.
4614
+ */
4615
+ function startRosterPolling(mesh) {
4616
+ heardAt.clear();
4617
+ repairedAt = -Infinity;
4618
+ // `peer` is the verified author's DID with the device its payload names:
4619
+ // a beat can only vouch for its own agent's devices. Only devices the
4620
+ // poll tracks are recorded, so a stranger's beats cannot grow the map.
4621
+ mesh.on("beat", (peer) => {
4622
+ if (meshManager === mesh && heardAt.has(peer))
4623
+ heardAt.set(peer, Date.now());
4624
+ });
4625
+ mesh.beat();
4626
+ beatInterval = setInterval(() => mesh.beat(), BEAT_INTERVAL_MS);
4466
4627
  // Immediate first poll, then periodic
4467
4628
  void pollRoster();
4468
4629
  rosterInterval = setInterval(() => void pollRoster(), ROSTER_POLL_INTERVAL_MS);
4469
4630
  }
4631
+ /** Stop the roster poll and the beat. Beats are never persisted: nothing else to undo. */
4470
4632
  function stopRosterPolling() {
4471
4633
  if (rosterInterval !== null) {
4472
4634
  clearInterval(rosterInterval);
4473
4635
  rosterInterval = null;
4474
4636
  }
4637
+ if (beatInterval !== null) {
4638
+ clearInterval(beatInterval);
4639
+ beatInterval = null;
4640
+ }
4475
4641
  }
4476
4642
  // ── Mesh wiring helpers ─────────────────────────────────────────
4477
4643
  function wireMeshEvents(mesh) {
@@ -4644,7 +4810,7 @@ function createSession(config) {
4644
4810
  await withdrawCallPresence();
4645
4811
  throw new Error("Session destroyed");
4646
4812
  }
4647
- startRosterPolling();
4813
+ startRosterPolling(mesh);
4648
4814
  emit("topology-changed", "mesh");
4649
4815
  setState("active");
4650
4816
  return;
@@ -4876,11 +5042,16 @@ class NeighbourhoodProxy {
4876
5042
  async sendSignalU(remoteAgentDid, payload) {
4877
5043
  return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sendSignalU(__classPrivateFieldGet$a(this, _NeighbourhoodProxy_pID, "f"), remoteAgentDid, payload);
4878
5044
  }
4879
- /** Broadcast a signed signal to all agents in the neighbourhood. */
5045
+ /**
5046
+ * Broadcast a signed signal to all agents in the neighbourhood. The
5047
+ * sender's own agent gets it too (its other clients hear it), so a handler
5048
+ * that must not act on its own messages drops them by author or device;
5049
+ * `loopback` adds a second copy for the sender's executor.
5050
+ */
4880
5051
  async sendBroadcast(payload, loopback = false) {
4881
5052
  return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sendBroadcast(__classPrivateFieldGet$a(this, _NeighbourhoodProxy_pID, "f"), payload, loopback);
4882
5053
  }
4883
- /** Broadcast an unsigned signal to all agents in the neighbourhood. */
5054
+ /** Broadcast an unsigned signal to all agents in the neighbourhood; delivered as {@link sendBroadcast}. */
4884
5055
  async sendBroadcastU(payload, loopback = false) {
4885
5056
  return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sendBroadcastU(__classPrivateFieldGet$a(this, _NeighbourhoodProxy_pID, "f"), payload, loopback);
4886
5057
  }
@@ -5589,7 +5760,10 @@ class SHACLShape {
5589
5760
  const statements = (source) => links
5590
5761
  .filter(l => l.source === source && l.predicate !== 'sh://property')
5591
5762
  .flatMap(l => l.predicate === 'sh://in'
5592
- ? [`sh:in ( ${JSON.parse(l.target.slice(15)).map((v) => str(v.value)).join(' ')} )`, `ad4m:in ${obj(l)}`]
5763
+ ? [`sh:in ( ${JSON.parse(l.target.slice(15)).map((v) => {
5764
+ const value = v !== null && typeof v === 'object' && 'value' in v ? v.value : v;
5765
+ return typeof value === 'string' ? str(value) : JSON.stringify(value);
5766
+ }).join(' ')} )`, `ad4m:in ${obj(l)}`]
5593
5767
  : [`${pred(l.predicate)} ${obj(l)}`]);
5594
5768
  const properties = links
5595
5769
  .filter(l => l.source === this.nodeShapeUri && l.predicate === 'sh://property')
@@ -5828,7 +6002,8 @@ class SHACLShape {
5828
6002
  target: prop.class
5829
6003
  });
5830
6004
  }
5831
- if (prop.in && prop.in.length > 0) {
6005
+ // `in: []` is a deny-all constraint, not the absence of one — store it.
6006
+ if (prop.in !== undefined) {
5832
6007
  links.push({
5833
6008
  source: propShapeId,
5834
6009
  predicate: "sh://in",
@@ -6297,8 +6472,10 @@ isAbstract) {
6297
6472
  if (propMeta.flag && propMeta.initial) {
6298
6473
  propShape.hasValue = propMeta.initial;
6299
6474
  }
6300
- // sh:in — allowed values (enum constraint)
6301
- if (propMeta.options && propMeta.options.length > 0) {
6475
+ // sh:in — allowed values (enum constraint). An explicit empty list
6476
+ // is kept: it denies every value, which dropping would widen to
6477
+ // unconstrained.
6478
+ if (propMeta.options !== undefined) {
6302
6479
  propShape.in = propMeta.options;
6303
6480
  }
6304
6481
  // AD4M-specific metadata
@@ -9457,6 +9634,15 @@ class PerspectiveProxy {
9457
9634
  invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
9458
9635
  return result;
9459
9636
  }
9637
+ /**
9638
+ * Drops an open batch without committing it — the recovery for a failed batched call:
9639
+ * a failed call does not roll back the calls before it and may have staged part of its
9640
+ * own work, so discard rather than commit to keep the successful calls. Resolves `true`
9641
+ * when the batch was open and is now dropped.
9642
+ */
9643
+ async discardBatch(batchId) {
9644
+ return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").discardBatch(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, batchId);
9645
+ }
9460
9646
  /**
9461
9647
  * Retrieves and renders an Expression referenced in this perspective.
9462
9648
  *
@@ -10063,6 +10249,60 @@ class PerspectiveProxy {
10063
10249
  await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").updateSubject(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, className, exprAddr, JSON.stringify(values), batchId);
10064
10250
  invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10065
10251
  }
10252
+ /**
10253
+ * Creates an instance of a subject class, validated by the executor against the class's
10254
+ * SHACL shape before anything is written (each property's type, which are required, which
10255
+ * take a single value, `sh:in`): the same check as the MCP `instance_create` tool. A refused
10256
+ * write rejects with an `RpcError` whose `data` is an `InstanceError` (status 422 and
10257
+ * `kind: 'validation'` for a shape violation, with one `ValidationError` per property) and
10258
+ * stages nothing. With `batchId` a non-validation failure can leave part of the write
10259
+ * staged in the batch — discard it ({@link discardBatch}), don't commit it to keep
10260
+ * earlier calls. An instance created in the same batch is not found — existence reads
10261
+ * committed state only — so a create followed by an update, remove or
10262
+ * `instanceAddToCollection` of the new instance in one batch fails `notFound`; put a new
10263
+ * instance's initial collection items on the create itself.
10264
+ *
10265
+ * @example
10266
+ * const { baseUri } = await perspective.instanceCreate({ className: "Task", properties: { title: "Write" } });
10267
+ */
10268
+ async instanceCreate(body) {
10269
+ const created = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceCreate(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10270
+ invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10271
+ return created;
10272
+ }
10273
+ /** Sets single-valued properties of an instance, validated; the others stay. See {@link instanceCreate}. */
10274
+ async instanceUpdate(body) {
10275
+ const updated = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceUpdate(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10276
+ invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10277
+ return updated;
10278
+ }
10279
+ /** Removes an instance and every link to and from it. See {@link instanceCreate}. */
10280
+ async instanceRemove(body) {
10281
+ // Outside a batch the links go one by one, so a rejection (`partiallyRemoved`) can
10282
+ // come after some are gone: invalidate either way.
10283
+ try {
10284
+ return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceRemove(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10285
+ }
10286
+ finally {
10287
+ invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10288
+ }
10289
+ }
10290
+ /** Adds an item to a collection of an instance, validated. See {@link instanceCreate}. */
10291
+ async instanceAddToCollection(body) {
10292
+ const added = await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceAddToCollection(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10293
+ invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10294
+ return added;
10295
+ }
10296
+ /** Removes an item from a collection of an instance. See {@link instanceCreate}. */
10297
+ async instanceRemoveFromCollection(body) {
10298
+ // Like instanceRemove, a rejection can come after some links are gone.
10299
+ try {
10300
+ return await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").instanceRemoveFromCollection(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, body);
10301
+ }
10302
+ finally {
10303
+ invalidatePerspectiveCache(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid);
10304
+ }
10305
+ }
10066
10306
  async getSubjectData(subjectClass, exprAddr) {
10067
10307
  if (typeof subjectClass === "string") {
10068
10308
  return JSON.parse(await __classPrivateFieldGet$7(this, _PerspectiveProxy_client, "f").getSubjectData(__classPrivateFieldGet$7(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ className: subjectClass }), exprAddr));
@@ -10560,7 +10800,9 @@ class PerspectiveProxy {
10560
10800
  required: minCount > 0,
10561
10801
  collection: isCollection,
10562
10802
  writable,
10563
- ...(options && options.length > 0 ? { options } : {}),
10803
+ // `options: []` means "allows nothing" — keep it distinct
10804
+ // from an absent constraint.
10805
+ ...(options !== undefined ? { options } : {}),
10564
10806
  };
10565
10807
  });
10566
10808
  return { className: safeName, shapeUri, properties };
@@ -10609,7 +10851,7 @@ class PerspectiveProxy {
10609
10851
  return {};
10610
10852
  const result = {};
10611
10853
  for (const prop of shape.properties) {
10612
- if (prop.options && prop.options.length > 0) {
10854
+ if (prop.options !== undefined) {
10613
10855
  result[prop.name] = prop.options;
10614
10856
  }
10615
10857
  }
@@ -11031,6 +11273,42 @@ class PerspectiveClient {
11031
11273
  async removeSubject(uuid, subjectClass, expressionAddress, batchId) {
11032
11274
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.removeSubject', { uuid, subjectClass, expressionAddress, batchId });
11033
11275
  }
11276
+ /**
11277
+ * Validated writes (`perspective.instance*`): the executor checks each against the class's
11278
+ * SHACL shape — each property's type, which are required, which take a single value, `sh:in`
11279
+ * — before writing anything. A refused write rejects with an `RpcError` whose `data` is an
11280
+ * `InstanceError` and stages nothing for that call; a shape violation is status 422 with
11281
+ * `data.kind === 'validation'` and `data.errors` naming each property.
11282
+ *
11283
+ * With `batchId` the write is staged into that open batch and lands on its commit; the
11284
+ * link reads a write does (collection membership, the remove cascade) see the batch's own
11285
+ * staged work, but an instance created in the same batch is not found — instance existence
11286
+ * reads committed state only, so a create followed by an update, remove or
11287
+ * `instanceAddToCollection` of the new instance in one batch fails `notFound`; put a new
11288
+ * instance's initial collection items on the create itself. A failure that is not a
11289
+ * refusal — a store error mid-write, `failed` / `partiallyRemoved` — can leave part of the
11290
+ * write staged in the batch: discard it ({@link discardBatch}) instead of committing
11291
+ * it to keep the calls that succeeded.
11292
+ */
11293
+ async instanceCreate(uuid, body) {
11294
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceCreate', { uuid, ...body });
11295
+ }
11296
+ /** Sets the given single-valued properties; the others stay. See {@link instanceCreate}. */
11297
+ async instanceUpdate(uuid, body) {
11298
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceUpdate', { uuid, ...body });
11299
+ }
11300
+ /** Removes the instance and every link to and from it. See {@link instanceCreate}. */
11301
+ async instanceRemove(uuid, body) {
11302
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceRemove', { uuid, ...body });
11303
+ }
11304
+ /** Adds an item to a collection (a no-op when it is a member). See {@link instanceCreate}. */
11305
+ async instanceAddToCollection(uuid, body) {
11306
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceAddToCollection', { uuid, ...body });
11307
+ }
11308
+ /** Removes an item's membership link from a collection. See {@link instanceCreate}. */
11309
+ async instanceRemoveFromCollection(uuid, body) {
11310
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.instanceRemoveFromCollection', { uuid, ...body });
11311
+ }
11034
11312
  async getSubjectData(uuid, subjectClass, expressionAddress) {
11035
11313
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.getSubjectData', { uuid, subjectClass, expressionAddress });
11036
11314
  }
@@ -11092,6 +11370,15 @@ class PerspectiveClient {
11092
11370
  const diff = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.commitBatch', { uuid, batchId });
11093
11371
  return LinkExpressionMutations.fromWire(diff);
11094
11372
  }
11373
+ /**
11374
+ * Drops an open batch without committing it — the recovery for a failed batched call:
11375
+ * a failed call does not roll back the calls before it and may have staged part of its
11376
+ * own work, so discard rather than commit to keep the successful calls. Resolves `true`
11377
+ * when the batch was open and is now dropped.
11378
+ */
11379
+ async discardBatch(uuid, batchId) {
11380
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.discardBatch', { uuid, batchId });
11381
+ }
11095
11382
  /** Register a callback that fires after a successful WebSocket reconnect.
11096
11383
  * Passes through to ApiClient.onReconnect(). Returns an unsubscribe function. */
11097
11384
  onReconnect(callback) {
@@ -11139,9 +11426,29 @@ class RuntimeClient {
11139
11426
  async tlsDomain() {
11140
11427
  return __classPrivateFieldGet$5(this, _RuntimeClient_apiClient, "f").call('runtime.tlsDomain', {});
11141
11428
  }
11429
+ /** Stops the executor (exit 0). Only the operator on the executor's machine. */
11142
11430
  async quit() {
11143
11431
  return __classPrivateFieldGet$5(this, _RuntimeClient_apiClient, "f").call('runtime.quit', {});
11144
11432
  }
11433
+ /** Answers, then the executor exits 75 and its supervisor starts it again. */
11434
+ async restart() {
11435
+ return __classPrivateFieldGet$5(this, _RuntimeClient_apiClient, "f").call('runtime.restart', {});
11436
+ }
11437
+ /** The newest lines (at most 2000) of the executor's log file (`--log-dir`). */
11438
+ async logTail(lines) {
11439
+ return __classPrivateFieldGet$5(this, _RuntimeClient_apiClient, "f").call('runtime.logTail', { lines });
11440
+ }
11441
+ /** The executor's config file: its values, every key with its class, and whether a write waits for a restart. */
11442
+ async config() {
11443
+ return __classPrivateFieldGet$5(this, _RuntimeClient_apiClient, "f").call('runtime.config', {});
11444
+ }
11445
+ /**
11446
+ * Writes keys to the executor's config file (`--config`); they take effect at the next
11447
+ * start. A `machine` key from a caller off the executor's machine is refused `local-only`.
11448
+ */
11449
+ async setConfig(set, unset) {
11450
+ return __classPrivateFieldGet$5(this, _RuntimeClient_apiClient, "f").call('runtime.setConfig', { set, unset });
11451
+ }
11145
11452
  async openLink(url) {
11146
11453
  return __classPrivateFieldGet$5(this, _RuntimeClient_apiClient, "f").call('runtime.openLink', { url });
11147
11454
  }
@@ -18935,6 +19242,23 @@ class IdentityClient {
18935
19242
  async devices() {
18936
19243
  return __classPrivateFieldGet$2(this, _IdentityClient_apiClient, "f").call("identity.devices", {});
18937
19244
  }
19245
+ /**
19246
+ * A new main wallet key for this executor, so a revoked executor can link again. The old
19247
+ * key stays for history. Only the operator on the executor's machine (the admin credential
19248
+ * on a loopback listener). A caller without the admin credential gets 403 "Admin credential
19249
+ * required"; the admin credential on a network listener gets 403 `local-only`.
19250
+ */
19251
+ async rekey() {
19252
+ return __classPrivateFieldGet$2(this, _IdentityClient_apiClient, "f").call("identity.rekey", {});
19253
+ }
19254
+ /**
19255
+ * The custody channel: the main agent's device keys (public keys only), the keys a master
19256
+ * key sent to this computer is sealed to. Only the admin credential on a loopback listener
19257
+ * of an executor started with `--custody-channel`; any other caller gets 403.
19258
+ */
19259
+ async custodyStatus() {
19260
+ return __classPrivateFieldGet$2(this, _IdentityClient_apiClient, "f").call("identity.custodyStatus", {});
19261
+ }
18938
19262
  }
18939
19263
  _IdentityClient_apiClient = new WeakMap();
18940
19264
 
@@ -24731,6 +25055,14 @@ class WakerSubscriptionManager {
24731
25055
  * keeps persisting them so a restart restores them (#1595).
24732
25056
  */
24733
25057
  this.reopening = new Map();
25058
+ /**
25059
+ * Mention subscriptions listening through their mention query only, because
25060
+ * their text query failed to open (#1735: a TextContent `contains` scan over a
25061
+ * large neighbourhood can take longer than the handshake budget). The text
25062
+ * query alone is re-attempted: `timer` is the wait before the next attempt,
25063
+ * `proxy` the attempt in flight. `release()` cancels both.
25064
+ */
25065
+ this.textRetries = new Map();
24734
25066
  /**
24735
25067
  * Cancellation tokens for in-flight `subscribe()` calls.
24736
25068
  *
@@ -24789,6 +25121,15 @@ class WakerSubscriptionManager {
24789
25121
  * If a subscription with the same id already exists, it is disposed first.
24790
25122
  */
24791
25123
  async subscribe(sub) {
25124
+ // The manager's own copy: it records `textHistoryRead` on it. A re-derived
25125
+ // subscription under the same id keeps what the manager knows of its text
25126
+ // query.
25127
+ const prior = this.activeSubscriptions.get(sub.id) ??
25128
+ this.pendingSubscriptions.get(sub.id) ??
25129
+ this.reopening.get(sub.id)?.sub;
25130
+ sub = { ...sub };
25131
+ if (prior?.textHistoryRead && sub.textHistoryRead === undefined)
25132
+ sub.textHistoryRead = true;
24792
25133
  // Dispose existing subscription with same id if any. Not `dispose()`: a
24793
25134
  // re-attempt must not start the backoff over.
24794
25135
  this.release(sub.id, false);
@@ -24810,12 +25151,15 @@ class WakerSubscriptionManager {
24810
25151
  if (sub.mentionQuery) {
24811
25152
  this.logger.info(`[waker] ${sub.id}: model query over ${sub.mentionClass}:\n${sub.mentionQuery}`);
24812
25153
  }
24813
- const proxy = sub.className
25154
+ const textProxy = () => sub.className
24814
25155
  ? new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient, sub.className)
24815
25156
  : new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
25157
+ const proxy = textProxy();
24816
25158
  const mentionProxy = sub.mentionQuery
24817
25159
  ? new QuerySubscriptionProxy(sub.perspective, sub.mentionQuery, this.perspectiveClient, sub.mentionClass)
24818
25160
  : undefined;
25161
+ // The live proxies. A text query that failed while the mention query opened
25162
+ // leaves it, and joins it again once a re-attempt opens (#1735).
24819
25163
  const proxies = mentionProxy ? [proxy, mentionProxy] : [proxy];
24820
25164
  // `cancelOpening`: a handshake given up on must not keep the executor
24821
25165
  // computing a first result nobody reads; abandoned ones piled up into
@@ -24828,28 +25172,49 @@ class WakerSubscriptionManager {
24828
25172
  catch { }
24829
25173
  }
24830
25174
  };
24831
- // Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
24832
- // rejects this promise internally when subscribe() fails, and if nobody catches
24833
- // it before the next microtask it crashes the process.
24834
- for (const p of proxies) {
24835
- if (p.initialized && typeof p.initialized.catch === "function")
24836
- p.initialized.catch(() => { });
24837
- }
24838
- // One deadline for the whole handshake: `proxy.subscribe()` and the
25175
+ // One deadline per query's handshake: `proxy.subscribe()` and the
24839
25176
  // `initialized` promise it resolves share the budget, so a hang in either
24840
25177
  // surfaces as the same loud-but-recoverable failure a rejection does.
24841
- const budgetMs = this.subscribeTimeoutMs;
24842
- const startedAt = Date.now();
24843
- const bounded = (step, what) => budgetMs > 0
24844
- ? withTimeout(step, Math.max(0, budgetMs - (Date.now() - startedAt)), `${what} timed out after ${budgetMs}ms`)
24845
- : step;
24846
- try {
24847
- await bounded(Promise.all(proxies.map((p) => p.subscribe())), "subscribe handshake");
24848
- if (this.isStale(sub.id, token)) {
24849
- disposeProxies();
25178
+ const open = async (p, budgetMs) => {
25179
+ // Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
25180
+ // rejects this promise internally when subscribe() fails, and if nobody catches
25181
+ // it before the next microtask it crashes the process.
25182
+ if (p.initialized && typeof p.initialized.catch === "function")
25183
+ p.initialized.catch(() => { });
25184
+ const startedAt = Date.now();
25185
+ const bounded = (step, what) => budgetMs > 0
25186
+ ? withTimeout(step, Math.max(0, budgetMs - (Date.now() - startedAt)), `${what} timed out after ${budgetMs}ms`)
25187
+ : step;
25188
+ await bounded(p.subscribe(), "subscribe handshake");
25189
+ // Stale: the caller disposes the proxies.
25190
+ if (this.isStale(sub.id, token))
24850
25191
  return;
25192
+ await bounded(p.initialized, "subscription initialization");
25193
+ };
25194
+ // A mention subscription's two queries open independently: on a large
25195
+ // neighbourhood the text query (a `contains` scan over every TextContent)
25196
+ // can take longer than the budget while the mention query answers in under
25197
+ // a second (#1735). Waiting on both made the whole subscription fail, and
25198
+ // the agent got no wake at all, not even through a mention link. The
25199
+ // mention query decides; a text query that fails is re-attempted on its own
25200
+ // once the subscription listens.
25201
+ const openings = proxies.map((p) => open(p, this.subscribeTimeoutMs));
25202
+ for (const o of openings)
25203
+ o.catch(() => { });
25204
+ let textFailure;
25205
+ try {
25206
+ await openings[openings.length - 1];
25207
+ if (mentionProxy) {
25208
+ const [text] = await Promise.allSettled([openings[0]]);
25209
+ if (text.status === "rejected") {
25210
+ textFailure = text.reason?.message ?? String(text.reason);
25211
+ try {
25212
+ proxy.dispose({ cancelOpening: true });
25213
+ }
25214
+ catch { }
25215
+ proxies.splice(proxies.indexOf(proxy), 1);
25216
+ }
24851
25217
  }
24852
- await bounded(Promise.all(proxies.map((p) => p.initialized)), "subscription initialization");
24853
25218
  }
24854
25219
  catch (err) {
24855
25220
  const msg = err?.message ?? String(err);
@@ -24894,10 +25259,14 @@ class WakerSubscriptionManager {
24894
25259
  if (seen.size > 0) {
24895
25260
  this.logger.info(`[waker] ${sub.id}: seeded ${seen.size} seen message(s) from persisted state`);
24896
25261
  }
24897
- // `opening` is the result the subscription holds when it opens (`proxy.result`): `onResult`
24898
- // only reports later changes, so this is the one chance to see what was written meanwhile.
24899
25262
  // `of`: the query the result is from, for the log (a mention subscription has two).
24900
- const handleResult = async (result, opening = false, of = "") => {
25263
+ // `opening` marks the result the query holds when it opens (`proxy.result`): `onResult`
25264
+ // only reports later changes, so this is the one chance to see what was written meanwhile.
25265
+ // A mention subscription reads it as `"history"` (recorded as seen, no wake) or `"news"`
25266
+ // (wakes on what is not seen yet: written while the waker was down).
25267
+ const handleResult = async (result, of, opening) => {
25268
+ if (this.isStale(sub.id, token))
25269
+ return;
24901
25270
  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)}`);
24902
25271
  // A model subscription delivers `{ instances }`, SPARQL an array of
24903
25272
  // rows. Anything else (e.g. `false` on a disconnect/reconnect) is
@@ -24932,8 +25301,8 @@ class WakerSubscriptionManager {
24932
25301
  this.logger.info(`[waker] ${sub.id}: no new mention among ${rows.length} items, skipping`);
24933
25302
  return;
24934
25303
  }
24935
- if (opening && !restored) {
24936
- // A new subscription: what it opens on is history, readable on demand, not news.
25304
+ if (opening === "history") {
25305
+ // What it opens on is history, readable on demand, not news.
24937
25306
  this.seenMessages.set(sub.id, currentSeen);
24938
25307
  const done = this.delivered.get(sub.id) ?? new Set();
24939
25308
  for (const address of newMessages)
@@ -24953,6 +25322,10 @@ class WakerSubscriptionManager {
24953
25322
  (ancestors.length ? `; ancestors: ${ancestors.join(", ")}` : ""));
24954
25323
  mentions.push({ address: msgAddr, parents, ancestors, ...provenance.get(msgAddr) });
24955
25324
  }
25325
+ // Released, or replaced under the same id, during the lookups: the state under `sub.id`
25326
+ // is no longer this subscription's, so write nothing and wake for nothing.
25327
+ if (this.isStale(sub.id, token))
25328
+ return;
24956
25329
  this.seenMessages.set(sub.id, currentSeen);
24957
25330
  const pending = this.undelivered.get(sub.id) ?? new Map();
24958
25331
  for (const mention of mentions)
@@ -24976,29 +25349,119 @@ class WakerSubscriptionManager {
24976
25349
  }, this.debounceMs));
24977
25350
  }
24978
25351
  };
24979
- proxy.onResult((result) => handleResult(result));
24980
- mentionProxy?.onResult((result) => handleResult(result, false, " (mention query)"));
24981
- for (const p of proxies) {
25352
+ // Read `p`'s opening result. The mention query's is news only after a restart. The text
25353
+ // query's is news only after a restart and once a text query of this subscription has read
25354
+ // its history (`textHistoryRead`): it may have listened without it, so the seen set may not
25355
+ // hold what the text query finds (#1735).
25356
+ const readOpening = async (p, of) => {
25357
+ if (p.result === undefined)
25358
+ return;
25359
+ const isText = p !== mentionProxy;
25360
+ const news = restored && (!isText || sub.type !== "mention" || sub.textHistoryRead === true);
25361
+ try {
25362
+ await handleResult(p.result, of, news ? "news" : "history");
25363
+ }
25364
+ catch (e) {
25365
+ this.logger.warn(`[waker] ${sub.id}: reading the opening result failed: ${e?.message ?? e}`);
25366
+ }
25367
+ const rows = sub.className ? p.result?.instances : p.result;
25368
+ if (isText && sub.type === "mention" && Array.isArray(rows) && !this.isStale(sub.id, token)) {
25369
+ sub.textHistoryRead = true;
25370
+ }
25371
+ };
25372
+ const listen = (p, of) => {
25373
+ p.onResult((result) => handleResult(result, of));
24982
25374
  p.onStatus?.((status) => this.onReopenStatus(sub, proxies, p, status));
24983
- }
25375
+ };
25376
+ if (proxies.includes(proxy))
25377
+ listen(proxy, "");
25378
+ if (mentionProxy)
25379
+ listen(mentionProxy, " (mention query)");
24984
25380
  if (this.isStale(sub.id, token)) {
24985
25381
  disposeProxies();
24986
25382
  return;
24987
25383
  }
24988
25384
  this.proxies.set(sub.id, proxies);
24989
25385
  this.activeSubscriptions.set(sub.id, sub);
25386
+ if (textFailure !== undefined) {
25387
+ // Re-attempt the text query alone, not the subscription: subscribing it
25388
+ // again would re-seed its seen set from the persisted one, and wake again
25389
+ // on mentions delivered since. Each failed attempt doubles the wait, up to
25390
+ // `maxRetryPendingMs`, between half and all of it, as `scheduleRetry` does.
25391
+ // The handshake budget doubles per failed attempt too: a scan that takes
25392
+ // longer than `subscribeTimeoutMs` (#1735 measured over 30 s) would
25393
+ // otherwise time out on every attempt. It is capped at `maxRetryPendingMs`
25394
+ // (or the first budget, if longer): with one attempt in flight at a time,
25395
+ // the executor then spends at most about as long on an attempt as the
25396
+ // waker waits between two.
25397
+ let ceiling = this.retryPendingMs;
25398
+ let budgetMs = this.subscribeTimeoutMs;
25399
+ const retryText = () => {
25400
+ const delayMs = ceiling / 2 + Math.random() * (ceiling / 2);
25401
+ ceiling = Math.min(ceiling * 2, this.maxRetryPendingMs);
25402
+ const attemptBudgetMs = budgetMs;
25403
+ budgetMs = Math.min(budgetMs * 2, Math.max(this.subscribeTimeoutMs, this.maxRetryPendingMs));
25404
+ const timer = setTimeout(async () => {
25405
+ if (this.textRetries.get(sub.id)?.timer !== timer || this.isStale(sub.id, token))
25406
+ return;
25407
+ const p = textProxy();
25408
+ this.textRetries.set(sub.id, { timer: null, proxy: p });
25409
+ // `release()` disposed it already when the entry no longer holds it.
25410
+ const ours = () => this.textRetries.get(sub.id)?.proxy === p;
25411
+ try {
25412
+ await open(p, attemptBudgetMs);
25413
+ }
25414
+ catch (err) {
25415
+ if (!ours())
25416
+ return;
25417
+ try {
25418
+ p.dispose({ cancelOpening: true });
25419
+ }
25420
+ catch { }
25421
+ if (this.isStale(sub.id, token)) {
25422
+ this.textRetries.delete(sub.id);
25423
+ return;
25424
+ }
25425
+ const nextMs = retryText();
25426
+ this.logger.debug(`[waker] ${sub.id}: text query failed again (${err?.message ?? err}); re-attempting in ${Math.round(nextMs / 1000)}s`);
25427
+ return;
25428
+ }
25429
+ if (!ours())
25430
+ return;
25431
+ this.textRetries.delete(sub.id);
25432
+ if (this.isStale(sub.id, token) || this.proxies.get(sub.id) !== proxies) {
25433
+ try {
25434
+ p.dispose({ cancelOpening: true });
25435
+ }
25436
+ catch { }
25437
+ return;
25438
+ }
25439
+ proxies.push(p);
25440
+ listen(p, "");
25441
+ this.logger.info(`[waker] ${sub.id}: text query opened; listening through both queries`);
25442
+ // The seen set is the mention query's, so a record it already woke on does not wake
25443
+ // again.
25444
+ await readOpening(p, "");
25445
+ if (!this.isStale(sub.id, token))
25446
+ this.persist();
25447
+ }, delayMs);
25448
+ if (typeof timer.unref === "function")
25449
+ timer.unref();
25450
+ this.textRetries.set(sub.id, { timer, proxy: null });
25451
+ return delayMs;
25452
+ };
25453
+ const firstMs = this.retryPendingMs > 0 ? retryText() : undefined;
25454
+ this.logger.warn(`[waker] ${sub.id}: text query failed (${textFailure}); listening through the mention query only, ` +
25455
+ (firstMs === undefined
25456
+ ? "not re-attempting the text query (retryPendingMs is 0)"
25457
+ : `re-attempting the text query in ${Math.round(firstMs / 1000)}s`));
25458
+ }
24990
25459
  // After a restart this wakes on mentions written while the waker was down; on a new
24991
25460
  // subscription it records the existing ones as history. The mention query's first, so a
24992
25461
  // record both hold wakes through its mention link.
24993
25462
  for (const [p, of] of [[mentionProxy, " (mention query)"], [proxy, ""]]) {
24994
- if (p?.result === undefined)
24995
- continue;
24996
- try {
24997
- await handleResult(p.result, true, of);
24998
- }
24999
- catch (e) {
25000
- this.logger.warn(`[waker] ${sub.id}: reading the opening result failed: ${e?.message ?? e}`);
25001
- }
25463
+ if (p && proxies.includes(p))
25464
+ await readOpening(p, of);
25002
25465
  }
25003
25466
  this.persist();
25004
25467
  this.logger.info(`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`);
@@ -25124,6 +25587,18 @@ class WakerSubscriptionManager {
25124
25587
  }
25125
25588
  }
25126
25589
  this.proxies.delete(id);
25590
+ const textRetry = this.textRetries.get(id);
25591
+ if (textRetry) {
25592
+ if (textRetry.timer)
25593
+ clearTimeout(textRetry.timer);
25594
+ try {
25595
+ textRetry.proxy?.dispose({ cancelOpening: true });
25596
+ }
25597
+ catch {
25598
+ /* ignore */
25599
+ }
25600
+ this.textRetries.delete(id);
25601
+ }
25127
25602
  this.reopening.delete(id);
25128
25603
  const timer = this.debounceTimers.get(id);
25129
25604
  if (timer) {