@coasys/ad4m 0.13.1-staging.4 → 0.13.1-staging.6

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 (63) hide show
  1. package/lib/index.cjs +807 -275
  2. package/lib/index.js +804 -276
  3. package/lib/src/Ad4mClient.d.ts +6 -0
  4. package/lib/src/Ad4mClient.js +8 -0
  5. package/lib/src/apiClient.d.ts +32 -0
  6. package/lib/src/apiClient.js +132 -13
  7. package/lib/src/generated/api/AgentMessage.d.ts +10 -0
  8. package/lib/src/generated/api/AgentMessage.js +2 -0
  9. package/lib/src/generated/api/AgentReply.d.ts +9 -0
  10. package/lib/src/generated/api/AgentReply.js +2 -0
  11. package/lib/src/generated/api/RpcMethods.d.ts +6 -0
  12. package/lib/src/generated/api/RpcMethods.js +1 -0
  13. package/lib/src/generated/api/RunAgentRequest.d.ts +26 -0
  14. package/lib/src/generated/api/RunAgentRequest.js +1 -0
  15. package/lib/src/generated/api/index.d.ts +3 -0
  16. package/lib/src/index.d.ts +1 -0
  17. package/lib/src/index.js +1 -0
  18. package/lib/src/model/Ad4mModel.d.ts +7 -0
  19. package/lib/src/model/Ad4mModel.js +16 -13
  20. package/lib/src/model/ModelQueryBuilder.d.ts +2 -0
  21. package/lib/src/model/ModelQueryBuilder.js +36 -57
  22. package/lib/src/model/types.d.ts +6 -0
  23. package/lib/src/neighbourhood/SfuManager.d.ts +15 -0
  24. package/lib/src/neighbourhood/SfuManager.js +39 -2
  25. package/lib/src/perspectives/LiveQuery.d.ts +40 -4
  26. package/lib/src/perspectives/LiveQuery.js +94 -10
  27. package/lib/src/perspectives/Mentioning.d.ts +37 -0
  28. package/lib/src/perspectives/Mentioning.js +58 -0
  29. package/lib/src/perspectives/PerspectiveClient.d.ts +26 -2
  30. package/lib/src/perspectives/PerspectiveClient.js +19 -4
  31. package/lib/src/perspectives/PerspectiveProxy.d.ts +34 -3
  32. package/lib/src/perspectives/PerspectiveProxy.js +52 -16
  33. package/lib/src/perspectives/TextContent.d.ts +4 -0
  34. package/lib/src/perspectives/TextContent.js +4 -0
  35. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +104 -12
  36. package/lib/src/perspectives/WakerSubscriptionManager.js +252 -66
  37. package/package.json +2 -2
  38. package/src/Ad4mClient.ts +9 -0
  39. package/src/apiClient.test.ts +467 -3
  40. package/src/apiClient.ts +133 -13
  41. package/src/generated/api/AgentMessage.ts +10 -0
  42. package/src/generated/api/AgentReply.ts +10 -0
  43. package/src/generated/api/RpcMethods.ts +4 -0
  44. package/src/generated/api/RunAgentRequest.ts +26 -0
  45. package/src/generated/api/index.ts +3 -0
  46. package/src/index.ts +1 -0
  47. package/src/model/Ad4mModel.test.ts +128 -364
  48. package/src/model/Ad4mModel.ts +16 -17
  49. package/src/model/ModelQueryBuilder.ts +39 -59
  50. package/src/model/types.ts +6 -0
  51. package/src/model/write-round-trips.test.ts +215 -0
  52. package/src/neighbourhood/SfuManager.test.ts +151 -2
  53. package/src/neighbourhood/SfuManager.ts +38 -1
  54. package/src/perspectives/LiveQuery.test.ts +173 -1
  55. package/src/perspectives/LiveQuery.ts +110 -10
  56. package/src/perspectives/Mentioning.test.ts +78 -0
  57. package/src/perspectives/Mentioning.ts +42 -0
  58. package/src/perspectives/PerspectiveClient.ts +36 -4
  59. package/src/perspectives/PerspectiveProxy.test.ts +24 -2
  60. package/src/perspectives/PerspectiveProxy.ts +61 -16
  61. package/src/perspectives/TextContent.ts +4 -0
  62. package/src/perspectives/WakerSubscriptionManager.test.ts +608 -152
  63. package/src/perspectives/WakerSubscriptionManager.ts +313 -67
package/lib/index.cjs CHANGED
@@ -109,6 +109,7 @@ const LONG_METHODS = new Set([
109
109
  "language.publish",
110
110
  "neighbourhood.join",
111
111
  "neighbourhood.publish",
112
+ "perspective.runAgent",
112
113
  "perspective.runInterpretation",
113
114
  "perspective.runInterpretationWithHarness",
114
115
  "runtime.restartHolochain",
@@ -132,6 +133,34 @@ const MAX_RECONNECT_DELAY_MS = 30000;
132
133
  * MAX_WATCH_RETRIES times in a row. */
133
134
  const WATCH_RETRY_DELAY_MS = 1000;
134
135
  const MAX_WATCH_RETRIES = 5;
136
+ /** An open socket sends a ping this often, and must deliver some message
137
+ * (the pong will do) within an interval of the first ping it left
138
+ * unanswered. After a network switch a socket can stay OPEN for minutes with
139
+ * no close event, since no FIN or RST ever arrives; this notices it within
140
+ * two intervals. */
141
+ const PING_INTERVAL_MS = 10000;
142
+ /** The slowest link a socket is given time for. The executor reads a ping
143
+ * only after the frames sent before it, so a ping left unanswered counts as
144
+ * silence only once everything the socket sent before that ping could have
145
+ * crossed this link and PONG_RETURN_MS more have passed, if that takes longer
146
+ * than PING_INTERVAL_MS. Messages that come in meanwhile do not shorten this:
147
+ * they say nothing about how far an upload has got. */
148
+ const SLOWEST_LINK_BYTES_PER_MS = 16; // 16 kB/s
149
+ /** How long a pong gets to come back after its ping could have been read
150
+ * behind a large write. Shorter than PING_INTERVAL_MS, so the few ms a small
151
+ * frame adds before a ping on an idle socket never cost a ping interval. */
152
+ const PONG_RETURN_MS = 5000;
153
+ /** The bytes `text` takes as UTF-8, as a WebSocket text frame sends it. */
154
+ function utf8Length(text) {
155
+ let bytes = text.length;
156
+ for (let i = 0; i < text.length; i++) {
157
+ const unit = text.charCodeAt(i);
158
+ // A surrogate is half of a 4-byte pair: 2 units, 2 extra bytes.
159
+ if (unit >= 0x80)
160
+ bytes += unit < 0x800 || (unit >= 0xd800 && unit <= 0xdfff) ? 1 : 2;
161
+ }
162
+ return bytes;
163
+ }
135
164
  let _idCounter = 0;
136
165
  function nextId() {
137
166
  return String(++_idCounter);
@@ -166,6 +195,14 @@ class ApiClient {
166
195
  this._wsReconnectTimer = null;
167
196
  this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;
168
197
  this._wsPingTimer = null;
198
+ /** When the open socket was first pinged since it last delivered a message; null while none is unanswered. */
199
+ this._wsPingedAt = null;
200
+ /** When that ping could have reached the executor, which reads it only after what the socket sent before it. */
201
+ this._wsPingArrivesBy = 0;
202
+ /** When everything the open socket sent so far could have crossed a SLOWEST_LINK_BYTES_PER_MS link.
203
+ * A message from the socket does not move it back: hearing from the executor says nothing
204
+ * about how much of a large upload has reached it. */
205
+ this._wsSentBy = 0;
169
206
  // The executor sends a socket only the events it asked for (`events.watch`).
170
207
  // What the executor has for the open socket, as sent; a new socket has `{}`.
171
208
  this._watching = '{}';
@@ -175,6 +212,13 @@ class ApiClient {
175
212
  this._watchSent = Promise.resolve();
176
213
  this._watchRetries = 0;
177
214
  this._watchRetryTimer = null;
215
+ this._wakeListening = false;
216
+ /** `online` always; `visibilitychange` only when the page became visible. */
217
+ this._onWake = (event) => {
218
+ if (event.type === 'visibilitychange' && typeof document !== 'undefined' && document.visibilityState !== 'visible')
219
+ return;
220
+ this.reconnectNow();
221
+ };
178
222
  this.baseUrl = baseUrl;
179
223
  this.token = token;
180
224
  this._webSocketImpl = webSocketImpl;
@@ -198,6 +242,9 @@ class ApiClient {
198
242
  return;
199
243
  if (this._authFailed !== null)
200
244
  throw new RpcError(401, this._authFailed);
245
+ // A dial ends any wait for one: a call or subscriber that dials during the backoff
246
+ // leaves no timer behind to swallow the retry after this socket's own drop.
247
+ this._cancelReconnect();
201
248
  const WsImpl = this._webSocketImpl ?? globalThis.WebSocket;
202
249
  const ws = new WsImpl(this._getWsUrl());
203
250
  this._ws = ws;
@@ -222,6 +269,8 @@ class ApiClient {
222
269
  // Only watchApplied() awaits this; a close before open is not an error otherwise.
223
270
  this._wsOpen.catch(() => { });
224
271
  ws.onmessage = (event) => {
272
+ if (this._ws === ws)
273
+ this._wsPingedAt = null;
225
274
  let parsed;
226
275
  try {
227
276
  parsed = JSON.parse(event.data);
@@ -247,7 +296,8 @@ class ApiClient {
247
296
  this._failAuth(rpcError.body);
248
297
  return;
249
298
  }
250
- if (parsed.type === 'pong')
299
+ // A dropped socket's events are not this client's any more: its successor watches again.
300
+ if (parsed.type === 'pong' || this._ws !== ws)
251
301
  return;
252
302
  const perspective = parsed.perspectiveUuid;
253
303
  const regs = this._handlers.get(parsed.type);
@@ -270,14 +320,14 @@ class ApiClient {
270
320
  if (this._ws !== ws)
271
321
  return;
272
322
  this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;
273
- this._startPing();
323
+ this._startPing(ws);
274
324
  // The watch goes out before the queued calls, so the events they cause reach listeners.
275
325
  this._watching = '{}';
276
326
  this._watchRetries = 0;
277
327
  this._flushWatch();
278
328
  for (const pending of this._pendingCalls.values()) {
279
329
  if (!pending.sent) {
280
- ws.send(pending.message);
330
+ this._send(ws, pending.message);
281
331
  pending.sent = true;
282
332
  }
283
333
  }
@@ -328,13 +378,40 @@ class ApiClient {
328
378
  for (const cb of [...this._authFailedCallbacks])
329
379
  callSafely(cb, 'Error in auth-failed callback:', reason);
330
380
  }
331
- _startPing() {
381
+ _startPing(ws) {
332
382
  this._stopPing();
383
+ this._wsPingedAt = null;
384
+ this._wsSentBy = 0;
333
385
  this._wsPingTimer = setInterval(() => {
334
- if (this._ws?.readyState === 1 /* OPEN */) {
335
- this._ws.send(JSON.stringify({ type: 'ping' }));
386
+ if (this._ws !== ws)
387
+ return;
388
+ const ping = JSON.stringify({ type: 'ping' });
389
+ if (this._wsPingedAt === null) {
390
+ this._wsPingedAt = performance.now();
391
+ this._send(ws, ping);
392
+ this._wsPingArrivesBy = this._wsSentBy;
393
+ return;
336
394
  }
337
- }, 30000);
395
+ if (performance.now() >= Math.max(this._wsPingedAt + PING_INTERVAL_MS, this._wsPingArrivesBy + PONG_RETURN_MS)) {
396
+ this._dropSilentSocket(ws);
397
+ return;
398
+ }
399
+ this._send(ws, ping);
400
+ }, PING_INTERVAL_MS);
401
+ }
402
+ /** Send on `ws`, counting how long what the open socket sent could take to cross the slowest link. */
403
+ _send(ws, text) {
404
+ if (this._ws === ws)
405
+ this._wsSentBy = Math.max(this._wsSentBy, performance.now()) + utf8Length(text) / SLOWEST_LINK_BYTES_PER_MS;
406
+ ws.send(text);
407
+ }
408
+ /** The socket answered nothing for a whole ping interval: treat it as
409
+ * closed now. Its close event can take minutes on a dead connection,
410
+ * since the close frame gets no answer either; `_onClose` ignores it then. */
411
+ _dropSilentSocket(ws) {
412
+ console.warn(`WebSocket silent for ${performance.now() - (this._wsPingedAt ?? performance.now())} ms after a ping; reconnecting`);
413
+ this._onClose(ws);
414
+ ws.close();
338
415
  }
339
416
  _stopPing() {
340
417
  if (this._wsPingTimer) {
@@ -349,8 +426,54 @@ class ApiClient {
349
426
  this._wsReconnectDelay = Math.min(this._wsReconnectDelay * 2, MAX_RECONNECT_DELAY_MS);
350
427
  this._wsReconnectTimer = setTimeout(() => {
351
428
  this._wsReconnectTimer = null;
429
+ this._listenForWake(false);
352
430
  this._ensureWs();
353
431
  }, delay);
432
+ this._listenForWake(true);
433
+ }
434
+ /** End the wait for the next dial, if one is pending, without dialling. */
435
+ _cancelReconnect() {
436
+ if (this._wsReconnectTimer) {
437
+ clearTimeout(this._wsReconnectTimer);
438
+ this._wsReconnectTimer = null;
439
+ }
440
+ this._listenForWake(false);
441
+ }
442
+ /**
443
+ * Dial now if the client is waiting out its reconnect backoff (up to 30 s)
444
+ * instead of letting the wait run out. For the moments the host knows the
445
+ * executor may be reachable again: an executor it restarted is up, the
446
+ * device woke. In a browser the client does this itself on `online` and when
447
+ * the page becomes visible. Does nothing while a socket is open or
448
+ * connecting, after `closeAll()` with nothing to reconnect, or once the
449
+ * executor refused the token.
450
+ */
451
+ reconnectNow() {
452
+ if (!this._wsReconnectTimer || this._ws || this._authFailed !== null)
453
+ return;
454
+ this._cancelReconnect();
455
+ // The executor is likely back, so a failure now starts the backoff over.
456
+ this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;
457
+ this._ensureWs();
458
+ }
459
+ /** Listen for `online` and `visibilitychange` exactly while a reconnect
460
+ * timer is pending. Outside a browser (no `window`) it registers nothing. */
461
+ _listenForWake(on) {
462
+ if (on === this._wakeListening)
463
+ return;
464
+ const win = typeof window !== 'undefined' ? window : undefined;
465
+ if (typeof win?.addEventListener !== 'function')
466
+ return;
467
+ const doc = typeof document !== 'undefined' && typeof document.addEventListener === 'function' ? document : undefined;
468
+ this._wakeListening = on;
469
+ if (on) {
470
+ win.addEventListener('online', this._onWake);
471
+ doc?.addEventListener('visibilitychange', this._onWake);
472
+ }
473
+ else {
474
+ win.removeEventListener('online', this._onWake);
475
+ doc?.removeEventListener('visibilitychange', this._onWake);
476
+ }
354
477
  }
355
478
  // ── RPC call method ─────────────────────────────────────────────────────
356
479
  /**
@@ -396,7 +519,7 @@ class ApiClient {
396
519
  }, timeoutMs);
397
520
  const onAbort = () => {
398
521
  if (pending.sent && this._ws?.readyState === 1 /* OPEN */) {
399
- this._ws.send(JSON.stringify({ id: nextId(), type: 'request.cancel', params: { targetId: id } }));
522
+ this._send(this._ws, JSON.stringify({ id: nextId(), type: 'request.cancel', params: { targetId: id } }));
400
523
  }
401
524
  settle(() => reject(new DOMException('Aborted', 'AbortError')));
402
525
  };
@@ -419,7 +542,7 @@ class ApiClient {
419
542
  return;
420
543
  }
421
544
  if (this._ws.readyState === 1 /* OPEN */) {
422
- this._ws.send(message);
545
+ this._send(this._ws, message);
423
546
  pending.sent = true;
424
547
  }
425
548
  });
@@ -540,10 +663,7 @@ class ApiClient {
540
663
  clearTimeout(this._watchRetryTimer);
541
664
  this._watchRetryTimer = null;
542
665
  }
543
- if (this._wsReconnectTimer) {
544
- clearTimeout(this._wsReconnectTimer);
545
- this._wsReconnectTimer = null;
546
- }
666
+ this._cancelReconnect();
547
667
  const ws = this._ws;
548
668
  this._ws = null;
549
669
  this._wsOpen = null;
@@ -1845,6 +1965,8 @@ class SfuManager {
1845
1965
  this.rosterUnsubscribe = null;
1846
1966
  this.dataChannelUnsubscribe = null;
1847
1967
  this.disconnectedTimer = null;
1968
+ /** Running while the room's roster leaves this agent out: see `noticeRoster`. */
1969
+ this.unlistedTimer = null;
1848
1970
  this.neighbourhood = neighbourhood;
1849
1971
  this.neighbourhoodUrl = neighbourhoodUrl || "";
1850
1972
  this.roomId = roomId;
@@ -2131,6 +2253,37 @@ class SfuManager {
2131
2253
  this.renegotiationUnsubscribe = null;
2132
2254
  this.rosterUnsubscribe?.();
2133
2255
  this.rosterUnsubscribe = null;
2256
+ this.clearUnlistedTimer();
2257
+ }
2258
+ clearUnlistedTimer() {
2259
+ if (this.unlistedTimer) {
2260
+ clearTimeout(this.unlistedTimer);
2261
+ this.unlistedTimer = null;
2262
+ }
2263
+ }
2264
+ /**
2265
+ * The room's roster no longer lists this agent while `pc` is the call's:
2266
+ * the server has dropped this session, and ICE may not say so. In E6
2267
+ * (CI job 53158) one of six sessions never started a rebuild after a
2268
+ * 20 s outage the server had dropped it for. Rebuild once the roster has
2269
+ * left this agent out for `UNLISTED_GRACE_MS`; a roster that lists it
2270
+ * again in that time cancels, since one published just before this
2271
+ * join landed can arrive after it.
2272
+ */
2273
+ noticeRoster(pc, dids) {
2274
+ if (dids.includes(this.agentDid)) {
2275
+ this.clearUnlistedTimer();
2276
+ return;
2277
+ }
2278
+ if (this.unlistedTimer)
2279
+ return;
2280
+ this.unlistedTimer = setTimeout(() => {
2281
+ this.unlistedTimer = null;
2282
+ if (this.state.peerConnection !== pc)
2283
+ return;
2284
+ console.info("SFU: the room no longer lists this session, rebuilding the call");
2285
+ void this.reconnect();
2286
+ }, SfuManager.UNLISTED_GRACE_MS);
2134
2287
  }
2135
2288
  /** Undo a join that failed part way: its subscription and its connection. */
2136
2289
  abandon(pc) {
@@ -2165,8 +2318,10 @@ class SfuManager {
2165
2318
  if (!ours(roster) || this.state.peerConnection !== pc)
2166
2319
  return;
2167
2320
  void joined.then(() => {
2168
- if (this.state.peerConnection === pc)
2169
- this.applyRoster(roster.participants, true);
2321
+ if (this.state.peerConnection !== pc)
2322
+ return;
2323
+ this.applyRoster(roster.participants, true);
2324
+ this.noticeRoster(pc, roster.participants);
2170
2325
  });
2171
2326
  });
2172
2327
  for (const unsubscribe of previous)
@@ -2380,6 +2535,8 @@ SfuManager.MAX_RECONNECTS = 3;
2380
2535
  SfuManager.REJOIN_WINDOW_MS = 120000;
2381
2536
  /** How long ICE may stay disconnected before a rebuild: the executor's `ICE_DISCONNECT_GRACE`. */
2382
2537
  SfuManager.DISCONNECT_GRACE_MS = 10000;
2538
+ /** How long the roster may leave this agent out before the call is rebuilt. */
2539
+ SfuManager.UNLISTED_GRACE_MS = 3000;
2383
2540
 
2384
2541
  /**
2385
2542
  * Peer-to-peer WebRTC mesh transport for the AD4M SDK Session interface.
@@ -6655,7 +6812,19 @@ var __classPrivateFieldGet$7 = (undefined && undefined.__classPrivateFieldGet) |
6655
6812
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
6656
6813
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6657
6814
  };
6658
- var _LiveQuery_instances, _LiveQuery_client, _LiveQuery_uuid, _LiveQuery_open, _LiveQuery_onResult, _LiveQuery_id, _LiveQuery_revision, _LiveQuery_result, _LiveQuery_started, _LiveQuery_disposed, _LiveQuery_generation, _LiveQuery_latest, _LiveQuery_buffer, _LiveQuery_unlisten, _LiveQuery_unreconnect, _LiveQuery_start, _LiveQuery_replace, _LiveQuery_receive, _LiveQuery_resync;
6815
+ var _LiveQuery_instances, _LiveQuery_client, _LiveQuery_uuid, _LiveQuery_open, _LiveQuery_onResult, _LiveQuery_id, _LiveQuery_revision, _LiveQuery_result, _LiveQuery_started, _LiveQuery_disposed, _LiveQuery_generation, _LiveQuery_latest, _LiveQuery_buffer, _LiveQuery_unlisten, _LiveQuery_unreconnect, _LiveQuery_opening, _LiveQuery_retryTimer, _LiveQuery_reopening, _LiveQuery_statusListeners, _LiveQuery_start, _LiveQuery_reopen, _LiveQuery_clearRetry, _LiveQuery_emit, _LiveQuery_replace, _LiveQuery_receive, _LiveQuery_resync;
6816
+ /** Delay before the first retry of a failed re-open; it doubles per failure. */
6817
+ const REOPEN_BASE_DELAY_MS = 1000;
6818
+ /** Longest delay between two re-open attempts. */
6819
+ const REOPEN_MAX_DELAY_MS = 60000;
6820
+ /** The delay before re-open attempt `failures + 1`: between half and all of
6821
+ * `REOPEN_BASE_DELAY_MS * 2^(failures - 1)`, capped at
6822
+ * `REOPEN_MAX_DELAY_MS`. The random half spreads the clients of a restarted
6823
+ * executor apart. */
6824
+ function reopenDelay(failures, random = Math.random) {
6825
+ const ceiling = Math.min(REOPEN_BASE_DELAY_MS * 2 ** Math.max(0, failures - 1), REOPEN_MAX_DELAY_MS);
6826
+ return ceiling / 2 + random() * ceiling / 2;
6827
+ }
6659
6828
  /** Apply one update to the last result. Query rows are a multiset: added rows are appended.
6660
6829
  * Throws when the update names an instance that neither the last result nor
6661
6830
  * the update holds: the last result was wrong, and the caller must resync. */
@@ -6692,10 +6861,14 @@ function applyUpdate(result, update) {
6692
6861
  * One live query on the executor. Holds the last result, applies each update
6693
6862
  * to it, calls `resyncSubscription` when a revision is missing, and opens a
6694
6863
  * new subscription after a reconnect (the executor ends a socket's
6695
- * subscriptions when it closes). `onResult` gets every result after the
6696
- * first; `start()` returns the first.
6864
+ * subscriptions when it closes). A re-open that fails (the executor is
6865
+ * still loading the perspective after a restart) is retried with backoff
6866
+ * until it succeeds or the query is disposed; `onStatus` listeners hear
6867
+ * about it (#1595). `onResult` gets every result after the first; `start()`
6868
+ * returns the first.
6697
6869
  */
6698
6870
  class LiveQuery {
6871
+ /** `open` subscribes on the executor; aborting its signal cancels the call. */
6699
6872
  constructor(client, uuid, open, onResult) {
6700
6873
  _LiveQuery_instances.add(this);
6701
6874
  _LiveQuery_client.set(this, void 0);
@@ -6713,45 +6886,73 @@ class LiveQuery {
6713
6886
  _LiveQuery_buffer.set(this, null);
6714
6887
  _LiveQuery_unlisten.set(this, void 0);
6715
6888
  _LiveQuery_unreconnect.set(this, void 0);
6889
+ // Aborts the subscribe call still in flight, for `dispose({ cancelOpening })`.
6890
+ _LiveQuery_opening.set(this, void 0);
6891
+ _LiveQuery_retryTimer.set(this, void 0);
6892
+ _LiveQuery_reopening.set(this, false);
6893
+ _LiveQuery_statusListeners.set(this, new Set()
6894
+ /** `open` subscribes on the executor; aborting its signal cancels the call. */
6895
+ );
6716
6896
  __classPrivateFieldSet$7(this, _LiveQuery_client, client, "f");
6717
6897
  __classPrivateFieldSet$7(this, _LiveQuery_uuid, uuid, "f");
6718
6898
  __classPrivateFieldSet$7(this, _LiveQuery_open, open, "f");
6719
6899
  __classPrivateFieldSet$7(this, _LiveQuery_onResult, onResult, "f");
6720
6900
  __classPrivateFieldSet$7(this, _LiveQuery_unlisten, client.onQueryUpdate(update => __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_receive).call(this, update)), "f");
6721
- __classPrivateFieldSet$7(this, _LiveQuery_unreconnect, client.onReconnect(() => {
6722
- this.start().catch(e => console.error('Error re-opening live query after reconnect:', e));
6723
- }), "f");
6901
+ __classPrivateFieldSet$7(this, _LiveQuery_unreconnect, client.onReconnect(() => __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_reopen).call(this)), "f");
6724
6902
  }
6725
6903
  get id() { return __classPrivateFieldGet$7(this, _LiveQuery_id, "f"); }
6726
6904
  get result() { return __classPrivateFieldGet$7(this, _LiveQuery_result, "f"); }
6905
+ /** Whether a re-open failed and the query is waiting to retry it. */
6906
+ get reopening() { return __classPrivateFieldGet$7(this, _LiveQuery_reopening, "f"); }
6907
+ /** Call `listener` on each failed re-open and when a re-open succeeds
6908
+ * after one failed. Returns a remover. */
6909
+ onStatus(listener) {
6910
+ __classPrivateFieldGet$7(this, _LiveQuery_statusListeners, "f").add(listener);
6911
+ return () => __classPrivateFieldGet$7(this, _LiveQuery_statusListeners, "f").delete(listener);
6912
+ }
6727
6913
  /** Open the subscription (again) and return its initial result. A start
6728
6914
  * that a newer one overtakes resolves with the newer one's result. */
6729
6915
  start() {
6730
6916
  var _a;
6917
+ __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_clearRetry).call(this);
6731
6918
  __classPrivateFieldSet$7(this, _LiveQuery_latest, __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_start).call(this, __classPrivateFieldSet$7(this, _LiveQuery_generation, (_a = __classPrivateFieldGet$7(this, _LiveQuery_generation, "f"), ++_a), "f")), "f");
6732
6919
  return __classPrivateFieldGet$7(this, _LiveQuery_latest, "f");
6733
6920
  }
6734
- dispose() {
6921
+ /** End the subscription. With `cancelOpening`, a subscribe call still in
6922
+ * flight is cancelled too, so the executor stops computing a first result
6923
+ * nobody waits for (#1595); the pending `start()` then rejects instead of
6924
+ * resolving with that result. */
6925
+ dispose(options = {}) {
6735
6926
  var _a;
6736
6927
  __classPrivateFieldSet$7(this, _LiveQuery_disposed, true, "f");
6737
6928
  __classPrivateFieldSet$7(this, _LiveQuery_generation, (_a = __classPrivateFieldGet$7(this, _LiveQuery_generation, "f"), _a++, _a), "f");
6929
+ __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_clearRetry).call(this);
6930
+ __classPrivateFieldGet$7(this, _LiveQuery_statusListeners, "f").clear();
6738
6931
  __classPrivateFieldGet$7(this, _LiveQuery_unlisten, "f").call(this);
6739
6932
  __classPrivateFieldGet$7(this, _LiveQuery_unreconnect, "f").call(this);
6933
+ if (options.cancelOpening)
6934
+ __classPrivateFieldGet$7(this, _LiveQuery_opening, "f")?.abort();
6740
6935
  if (__classPrivateFieldGet$7(this, _LiveQuery_id, "f"))
6741
6936
  __classPrivateFieldGet$7(this, _LiveQuery_client, "f").disposeQuerySubscription(__classPrivateFieldGet$7(this, _LiveQuery_uuid, "f"), __classPrivateFieldGet$7(this, _LiveQuery_id, "f")).catch(() => { });
6742
6937
  }
6743
6938
  }
6744
- _LiveQuery_client = new WeakMap(), _LiveQuery_uuid = new WeakMap(), _LiveQuery_open = new WeakMap(), _LiveQuery_onResult = new WeakMap(), _LiveQuery_id = new WeakMap(), _LiveQuery_revision = new WeakMap(), _LiveQuery_result = new WeakMap(), _LiveQuery_started = new WeakMap(), _LiveQuery_disposed = new WeakMap(), _LiveQuery_generation = new WeakMap(), _LiveQuery_latest = new WeakMap(), _LiveQuery_buffer = new WeakMap(), _LiveQuery_unlisten = new WeakMap(), _LiveQuery_unreconnect = new WeakMap(), _LiveQuery_instances = new WeakSet(), _LiveQuery_start = async function _LiveQuery_start(generation) {
6939
+ _LiveQuery_client = new WeakMap(), _LiveQuery_uuid = new WeakMap(), _LiveQuery_open = new WeakMap(), _LiveQuery_onResult = new WeakMap(), _LiveQuery_id = new WeakMap(), _LiveQuery_revision = new WeakMap(), _LiveQuery_result = new WeakMap(), _LiveQuery_started = new WeakMap(), _LiveQuery_disposed = new WeakMap(), _LiveQuery_generation = new WeakMap(), _LiveQuery_latest = new WeakMap(), _LiveQuery_buffer = new WeakMap(), _LiveQuery_unlisten = new WeakMap(), _LiveQuery_unreconnect = new WeakMap(), _LiveQuery_opening = new WeakMap(), _LiveQuery_retryTimer = new WeakMap(), _LiveQuery_reopening = new WeakMap(), _LiveQuery_statusListeners = new WeakMap(), _LiveQuery_instances = new WeakSet(), _LiveQuery_start = async function _LiveQuery_start(generation) {
6745
6940
  __classPrivateFieldSet$7(this, _LiveQuery_buffer, [], "f");
6941
+ const opening = new AbortController();
6942
+ __classPrivateFieldSet$7(this, _LiveQuery_opening, opening, "f");
6746
6943
  let subscribed;
6747
6944
  try {
6748
- subscribed = await __classPrivateFieldGet$7(this, _LiveQuery_open, "f").call(this);
6945
+ subscribed = await __classPrivateFieldGet$7(this, _LiveQuery_open, "f").call(this, opening.signal);
6749
6946
  }
6750
6947
  catch (e) {
6751
6948
  if (generation === __classPrivateFieldGet$7(this, _LiveQuery_generation, "f"))
6752
6949
  __classPrivateFieldSet$7(this, _LiveQuery_buffer, null, "f");
6753
6950
  throw e;
6754
6951
  }
6952
+ finally {
6953
+ if (__classPrivateFieldGet$7(this, _LiveQuery_opening, "f") === opening)
6954
+ __classPrivateFieldSet$7(this, _LiveQuery_opening, undefined, "f");
6955
+ }
6755
6956
  if (__classPrivateFieldGet$7(this, _LiveQuery_disposed, "f") || generation !== __classPrivateFieldGet$7(this, _LiveQuery_generation, "f")) {
6756
6957
  __classPrivateFieldGet$7(this, _LiveQuery_client, "f").disposeQuerySubscription(__classPrivateFieldGet$7(this, _LiveQuery_uuid, "f"), subscribed.subscriptionId).catch(() => { });
6757
6958
  // Disposed while opening (e.g. a newer subscribe() on the same
@@ -6761,6 +6962,46 @@ _LiveQuery_client = new WeakMap(), _LiveQuery_uuid = new WeakMap(), _LiveQuery_o
6761
6962
  __classPrivateFieldSet$7(this, _LiveQuery_id, subscribed.subscriptionId, "f");
6762
6963
  __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_replace).call(this, subscribed.revision, subscribed.result);
6763
6964
  return __classPrivateFieldGet$7(this, _LiveQuery_result, "f");
6965
+ }, _LiveQuery_reopen = function _LiveQuery_reopen(failures = 0) {
6966
+ if (__classPrivateFieldGet$7(this, _LiveQuery_disposed, "f"))
6967
+ return;
6968
+ const reopened = this.start();
6969
+ const generation = __classPrivateFieldGet$7(this, _LiveQuery_generation, "f");
6970
+ reopened.then(() => {
6971
+ if (__classPrivateFieldGet$7(this, _LiveQuery_disposed, "f") || generation !== __classPrivateFieldGet$7(this, _LiveQuery_generation, "f") || !__classPrivateFieldGet$7(this, _LiveQuery_reopening, "f"))
6972
+ return;
6973
+ __classPrivateFieldSet$7(this, _LiveQuery_reopening, false, "f");
6974
+ __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_emit).call(this, { state: 'open' });
6975
+ }, error => {
6976
+ if (__classPrivateFieldGet$7(this, _LiveQuery_disposed, "f") || generation !== __classPrivateFieldGet$7(this, _LiveQuery_generation, "f"))
6977
+ return;
6978
+ const retryInMs = reopenDelay(failures + 1);
6979
+ console.error(`Error re-opening live query (attempt ${failures + 1}), retrying in ${Math.round(retryInMs)}ms:`, error);
6980
+ __classPrivateFieldSet$7(this, _LiveQuery_reopening, true, "f");
6981
+ __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_emit).call(this, { state: 'reopening', error, retryInMs });
6982
+ const timer = setTimeout(() => {
6983
+ __classPrivateFieldSet$7(this, _LiveQuery_retryTimer, undefined, "f");
6984
+ __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_reopen).call(this, failures + 1);
6985
+ }, retryInMs);
6986
+ // Node: a pending retry must not keep the process alive.
6987
+ if (typeof timer?.unref === 'function')
6988
+ timer.unref();
6989
+ __classPrivateFieldSet$7(this, _LiveQuery_retryTimer, timer, "f");
6990
+ });
6991
+ }, _LiveQuery_clearRetry = function _LiveQuery_clearRetry() {
6992
+ if (__classPrivateFieldGet$7(this, _LiveQuery_retryTimer, "f") === undefined)
6993
+ return;
6994
+ clearTimeout(__classPrivateFieldGet$7(this, _LiveQuery_retryTimer, "f"));
6995
+ __classPrivateFieldSet$7(this, _LiveQuery_retryTimer, undefined, "f");
6996
+ }, _LiveQuery_emit = function _LiveQuery_emit(status) {
6997
+ for (const listener of [...__classPrivateFieldGet$7(this, _LiveQuery_statusListeners, "f")]) {
6998
+ try {
6999
+ listener(status);
7000
+ }
7001
+ catch (e) {
7002
+ console.error('Error in live query status listener:', e);
7003
+ }
7004
+ }
6764
7005
  }, _LiveQuery_replace = function _LiveQuery_replace(revision, result) {
6765
7006
  __classPrivateFieldSet$7(this, _LiveQuery_revision, revision, "f");
6766
7007
  __classPrivateFieldSet$7(this, _LiveQuery_result, result, "f");
@@ -6809,7 +7050,7 @@ _LiveQuery_client = new WeakMap(), _LiveQuery_uuid = new WeakMap(), _LiveQuery_o
6809
7050
  // Replace the subscription with a new one.
6810
7051
  if (!__classPrivateFieldGet$7(this, _LiveQuery_disposed, "f") && generation === __classPrivateFieldGet$7(this, _LiveQuery_generation, "f")) {
6811
7052
  __classPrivateFieldGet$7(this, _LiveQuery_client, "f").disposeQuerySubscription(__classPrivateFieldGet$7(this, _LiveQuery_uuid, "f"), id).catch(() => { });
6812
- this.start().catch(e => console.error('Error re-opening live query:', e));
7053
+ __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_reopen).call(this);
6813
7054
  }
6814
7055
  });
6815
7056
  };
@@ -7590,8 +7831,8 @@ class QuerySubscriptionProxy {
7590
7831
  _QuerySubscriptionProxy_initResolve.set(this, void 0);
7591
7832
  _QuerySubscriptionProxy_initReject.set(this, void 0);
7592
7833
  const open = className === undefined
7593
- ? () => client.subscribeQuery(uuid, query)
7594
- : () => client.modelSubscribe(uuid, className, query);
7834
+ ? (signal) => client.subscribeQuery(uuid, query, { signal })
7835
+ : (signal) => client.modelSubscribe(uuid, className, query, { signal });
7595
7836
  __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_live, new LiveQuery(client, uuid, open, result => __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliver).call(this, result)), "f");
7596
7837
  __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_initialized, new Promise((resolve, reject) => {
7597
7838
  __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_initResolve, resolve, "f");
@@ -7629,9 +7870,23 @@ class QuerySubscriptionProxy {
7629
7870
  __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_callbacks, "f").add(callback);
7630
7871
  return () => __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_callbacks, "f").delete(callback);
7631
7872
  }
7632
- /** End the subscription on the executor and drop all callbacks. */
7633
- dispose() {
7634
- __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_live, "f").dispose();
7873
+ /** Whether the query lost its subscription (a reconnect, a failed
7874
+ * resync), could not open it again yet and is retrying: `result` is then
7875
+ * not live. */
7876
+ get reopening() {
7877
+ return __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_live, "f").reopening;
7878
+ }
7879
+ /** Call `listener` on each failed re-open of the subscription and when a
7880
+ * re-open succeeds after one failed (see {@link LiveQueryStatus}).
7881
+ * Returns a remover. */
7882
+ onStatus(listener) {
7883
+ return __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_live, "f").onStatus(listener);
7884
+ }
7885
+ /** End the subscription on the executor and drop all callbacks. With
7886
+ * `cancelOpening`, a `subscribe()` still waiting on the executor is
7887
+ * cancelled too, and rejects. */
7888
+ dispose(options = {}) {
7889
+ __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_live, "f").dispose(options);
7635
7890
  __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_callbacks, "f").clear();
7636
7891
  }
7637
7892
  }
@@ -7883,6 +8138,19 @@ class PerspectiveProxy {
7883
8138
  observationId, emitDebugEvents, options) {
7884
8139
  return await __classPrivateFieldGet$6(this, _PerspectiveProxy_client, "f").runInterpretationWithHarness(__classPrivateFieldGet$6(this, _PerspectiveProxy_handle, "f").uuid, transcript, basePrefix, maxToolCalls, classes, modelOverride, undefined, observationId, emitDebugEvents, options);
7885
8140
  }
8141
+ /**
8142
+ * Ask a model something about this perspective, or ask it to change something, with the
8143
+ * executor's own tools — including the tools apps install for their records. It reads freely;
8144
+ * it writes only with the tools named in `settings.writeTools`, as you. Answers with the
8145
+ * model's final reply.
8146
+ *
8147
+ * @param messages the conversation so far, the person's request last
8148
+ * @param settings `context` (what the person is looking at), `writeTools`, `model`, `maxToolCalls`
8149
+ * @param options `signal` / `timeoutMs` (default {@link LONG_TIMEOUT_MS})
8150
+ */
8151
+ async runAgent(messages, settings, options) {
8152
+ return await __classPrivateFieldGet$6(this, _PerspectiveProxy_client, "f").runAgent(__classPrivateFieldGet$6(this, _PerspectiveProxy_handle, "f").uuid, messages, settings, options);
8153
+ }
7886
8154
  /**
7887
8155
  * Register a neighbourhood auto-processor on this perspective. The executor
7888
8156
  * then runs interpretation automatically over new source items (like Flux
@@ -8257,6 +8525,12 @@ class PerspectiveProxy {
8257
8525
  /**
8258
8526
  * Adds a pre-signed LinkExpression to the perspective.
8259
8527
  *
8528
+ * The executor checks the signature against `link.author` and stores the
8529
+ * verdict as `proof.valid`. If the same link (author, source, predicate,
8530
+ * target and timestamp) is already stored with a signature that verifies,
8531
+ * its stored proof is kept. The expression passed here is still returned
8532
+ * and, when Shared, committed to the neighbourhood as given.
8533
+ *
8260
8534
  * @param link - The signed LinkExpression to add
8261
8535
  * @param status - Whether the link should be shared
8262
8536
  * @param batchId - Optional batch ID to group this operation with others
@@ -8885,16 +9159,11 @@ class PerspectiveProxy {
8885
9159
  async stringOrTemplateObjectToSubjectClassName(subjectClass) {
8886
9160
  if (typeof subjectClass === "string")
8887
9161
  return subjectClass;
8888
- else {
8889
- let subjectClasses = await this.subjectClassesByTemplate(subjectClass);
8890
- if (subjectClasses[0]) {
8891
- return subjectClasses[0];
8892
- }
8893
- else {
8894
- //@ts-ignore
8895
- return subjectClass.className;
8896
- }
8897
- }
9162
+ // The @Model decorator names the class, as in createSubject: no lookup.
9163
+ // Only an undecorated object is matched by its properties.
9164
+ const obj = subjectClass;
9165
+ return obj.className || obj.constructor?.className || obj.constructor?.prototype?.className
9166
+ || (await this.subjectClassesByTemplate(obj))[0];
8898
9167
  }
8899
9168
  /**
8900
9169
  * Creates a new subject instance of the given subject class
@@ -9560,7 +9829,15 @@ class PerspectiveProxy {
9560
9829
  * refuses a Prolog query (400): Prolog live queries are not supported. */
9561
9830
  async subscribeQuery(query) {
9562
9831
  const subscription = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet$6(this, _PerspectiveProxy_client, "f"));
9563
- await subscription.subscribe();
9832
+ try {
9833
+ await subscription.subscribe();
9834
+ }
9835
+ catch (e) {
9836
+ // Nobody gets the proxy, so nobody can dispose it: left as is, it
9837
+ // would re-open on every reconnect and retry for good (#1595).
9838
+ subscription.dispose({ cancelOpening: true });
9839
+ throw e;
9840
+ }
9564
9841
  return subscription;
9565
9842
  }
9566
9843
  }
@@ -9652,8 +9929,9 @@ class PerspectiveClient {
9652
9929
  return JSON.parse(result);
9653
9930
  }
9654
9931
  /** Open a live SPARQL query. Updates arrive through {@link onQueryUpdate}. */
9655
- async subscribeQuery(uuid, query) {
9656
- return __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call('perspective.subscribeQuery', { uuid, query });
9932
+ /** `options.signal` cancels the call, and the executor stops computing the first result. */
9933
+ async subscribeQuery(uuid, query, options) {
9934
+ return __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call('perspective.subscribeQuery', { uuid, query }, options);
9657
9935
  }
9658
9936
  /** Every `query-subscription-update` event on this client's socket. */
9659
9937
  onQueryUpdate(cb) {
@@ -9686,8 +9964,9 @@ class PerspectiveClient {
9686
9964
  return JSON.parse(resultJson);
9687
9965
  }
9688
9966
  /** Open a live model query over one class or several. Updates arrive through {@link onQueryUpdate}. */
9689
- async modelSubscribe(uuid, className, queryJson) {
9690
- return __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, ...classParams(className), query_json: queryJson });
9967
+ /** `options.signal` cancels the call, and the executor stops computing the first result. */
9968
+ async modelSubscribe(uuid, className, queryJson, options) {
9969
+ return __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, ...classParams(className), query_json: queryJson }, options);
9691
9970
  }
9692
9971
  async add(name) {
9693
9972
  const handle = await __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call('perspective.create', { name });
@@ -9773,6 +10052,19 @@ class PerspectiveClient {
9773
10052
  emitDebugEvents,
9774
10053
  }, options);
9775
10054
  }
10055
+ /**
10056
+ * A conversation with a model in this perspective, using the executor's own tools: the tools
10057
+ * that read this perspective, and only the writing tools named in `writeTools`. Every tool a
10058
+ * session offers acts on this perspective alone, so tools about other perspectives, the agent
10059
+ * or the node (listing or publishing perspectives, the profile) are not available. Runs as the
10060
+ * caller, with the caller's capabilities, and answers with the model's final reply.
10061
+ *
10062
+ * Defaults to {@link LONG_TIMEOUT_MS}: an agent may read documentation and make many tool
10063
+ * calls before it answers.
10064
+ */
10065
+ async runAgent(uuid, messages, settings, options) {
10066
+ return __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call('perspective.runAgent', { uuid, messages, ...settings }, options);
10067
+ }
9776
10068
  /**
9777
10069
  * Register a neighbourhood auto-processor on this perspective. The executor's
9778
10070
  * watch loop then runs interpretation automatically over new source items
@@ -18563,6 +18855,9 @@ function buildSPARQLWhereFilters(metadata, _allRelationsMetadata, where) {
18563
18855
  * Allows building queries with a chainable interface and either
18564
18856
  * running them once or subscribing to real-time updates.
18565
18857
  */
18858
+ /** What a subscription compares to skip a callback whose results equal the
18859
+ * last ones emitted (a resync or a reconnect re-open of an unchanged result). */
18860
+ const fingerprint = (value) => JSON.stringify(value, (_, v) => (typeof v === 'function' ? undefined : v));
18566
18861
  /** Query builder for Ad4mModel queries.
18567
18862
  * Allows building queries with a fluent interface and either running them once
18568
18863
  * or subscribing to updates.
@@ -18617,6 +18912,10 @@ class ModelQueryBuilder {
18617
18912
  }
18618
18913
  return this.ctor.parseModelResult(this.perspective, raw, include, properties);
18619
18914
  }
18915
+ /** Snapshot instances for dirty tracking, as `execute` does for its rows. */
18916
+ takeSnapshots(instances) {
18917
+ this.ctor.takeSnapshots(instances, this.queryParams.include);
18918
+ }
18620
18919
  /** Ends the current subscription, if any, on the client and the executor. */
18621
18920
  dispose() {
18622
18921
  if (this.currentSubscription) {
@@ -18986,7 +19285,6 @@ class ModelQueryBuilder {
18986
19285
  this.dispose();
18987
19286
  const parseResults = (raw) => this.parse(raw);
18988
19287
  // Suppress callbacks whose parsed results equal the last ones emitted.
18989
- const fingerprint = (results) => JSON.stringify(results, (_, v) => (typeof v === 'function' ? undefined : v));
18990
19288
  let lastFingerprint = null;
18991
19289
  const { initial } = await this.live(this.queryParams, (raw) => {
18992
19290
  try {
@@ -19137,73 +19435,46 @@ class ModelQueryBuilder {
19137
19435
  *
19138
19436
  */
19139
19437
  async paginateSubscribe(pageSize, pageNumber, callback) {
19140
- // Clean up any existing subscription
19141
19438
  this.dispose();
19142
- // Subscribe to the full result set (no limit/offset) so the subscription
19143
- // detects changes anywhere in the dataset; each change re-reads the page.
19144
- const subscriptionParams = { ...(this.queryParams || {}) };
19145
- delete subscriptionParams.limit;
19146
- delete subscriptionParams.offset;
19147
- // Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)
19439
+ // Subscribe to the page itself. Since #1237 the executor re-runs a paged
19440
+ // subscription when a record outside the page starts or stops matching
19441
+ // (the `joins` and `scan` trigger rules), and a model result carries
19442
+ // `totalCount`, so a write outside the page still changes the result and
19443
+ // is pushed. Each page is built from the pushed rows: no second query, and
19444
+ // the executor hydrates one page per change rather than every match.
19445
+ // Pushes arrive in revision order, so the last callback is the latest
19446
+ // state (#1051). After dispose() the live query delivers nothing.
19148
19447
  const paginatedQuery = {
19149
19448
  ...(this.queryParams || {}),
19150
19449
  limit: pageSize,
19151
19450
  offset: pageSize * (pageNumber - 1),
19152
19451
  count: true,
19153
19452
  };
19154
- // One read in flight. A dispatch while a read is running sets `pending`
19155
- // so a fetch always completes after the last dispatch. The generation
19156
- // counter from #1020 dropped superseded fetches, but ordered them by
19157
- // start time rather than by how fresh the data they read was — two
19158
- // back-to-back dispatches could keep the fetch that saw 1 model and
19159
- // drop the one that saw 2, after which the server has nothing further
19160
- // to say (issue #1051 / CI: "Paginate callback did not see second model save").
19161
- // After dispose() no read starts and no result is delivered, including
19162
- // a read that was already in flight when dispose() ran.
19163
- let disposed = false;
19164
- let fetching = false;
19165
- let pending = false;
19166
- const processResults = async () => {
19167
- if (disposed)
19168
- return;
19169
- if (fetching) {
19170
- pending = true;
19171
- return;
19172
- }
19173
- fetching = true;
19453
+ // As subscribe(): a callback fires only when the rows or totalCount
19454
+ // differ from the last page emitted, not on a resync or a reconnect
19455
+ // re-open of an unchanged page.
19456
+ let lastFingerprint = null;
19457
+ const toPage = (raw) => {
19458
+ const results = this.parse(raw);
19459
+ const fp = fingerprint([results, raw?.totalCount]);
19460
+ this.takeSnapshots(results);
19461
+ return { page: { results, totalCount: raw?.totalCount, pageSize, pageNumber }, fp };
19462
+ };
19463
+ const { initial } = await this.live(paginatedQuery, (raw) => {
19174
19464
  try {
19175
- const { results, totalCount } = await this.execute(paginatedQuery);
19176
- if (!disposed)
19177
- callback({ results, totalCount, pageSize, pageNumber });
19465
+ const { page, fp } = toPage(raw);
19466
+ if (fp === lastFingerprint)
19467
+ return;
19468
+ lastFingerprint = fp;
19469
+ callback(page);
19178
19470
  }
19179
- finally {
19180
- fetching = false;
19181
- if (pending) {
19182
- pending = false;
19183
- // Detached from the caller's promise: needs its own handler, or a
19184
- // rejection here is unhandled.
19185
- processResults().catch(e => console.error('Paginate subscription error:', e));
19186
- }
19471
+ catch (e) {
19472
+ console.error('Paginate subscription error:', e);
19187
19473
  }
19188
- };
19189
- const { live } = await this.live(subscriptionParams, () => {
19190
- processResults().catch(e => console.error('Paginate subscription error:', e));
19191
19474
  });
19192
- if (this.currentSubscription === live) {
19193
- this.currentSubscription = {
19194
- dispose: () => {
19195
- disposed = true;
19196
- live.dispose();
19197
- },
19198
- };
19199
- }
19200
- else {
19201
- // Disposed, or overtaken by a later subscribe, while opening: deliver nothing.
19202
- disposed = true;
19203
- }
19204
- // Initial fetch (single call with count: true)
19205
- const { results, totalCount } = await this.execute(paginatedQuery);
19206
- return { results, totalCount, pageSize, pageNumber };
19475
+ const { page, fp } = toPage(initial);
19476
+ lastFingerprint = fp;
19477
+ return page;
19207
19478
  }
19208
19479
  /**
19209
19480
  * Subscribes to paginated results updates using SPARQL.
@@ -20365,6 +20636,20 @@ class Ad4mModel {
20365
20636
  return [];
20366
20637
  return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));
20367
20638
  }
20639
+ /**
20640
+ * Snapshot freshly built instances for dirty tracking, with the relations
20641
+ * `include` loaded (its `$`-prefixed projection keys are not relations).
20642
+ * Used by every query path, and by ModelQueryBuilder for pushed results.
20643
+ * @internal
20644
+ */
20645
+ static takeSnapshots(instances, include) {
20646
+ const relations = include
20647
+ ? Object.fromEntries(Object.entries(include).filter(([k]) => !k.startsWith('$')))
20648
+ : undefined;
20649
+ const snapshot = relations && Object.keys(relations).length > 0 ? relations : undefined;
20650
+ for (const inst of instances)
20651
+ inst.takeSnapshot?.(snapshot);
20652
+ }
20368
20653
  // ── One query over several classes (#1238) ────────────────────────────────
20369
20654
  /**
20370
20655
  * Build the wire parameters for one query over several classes.
@@ -20466,12 +20751,7 @@ class Ad4mModel {
20466
20751
  const { classNames, queryJson } = Ad4mModel.prepareUnionQueryParams(classes, query);
20467
20752
  const result = await perspective.modelQuery(classNames, queryJson, options);
20468
20753
  const results = Ad4mModel.parseUnionResult(classes, perspective, result, query.include, query.properties);
20469
- const snapshotRelations = query.include
20470
- ? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith('$')))
20471
- : undefined;
20472
- for (const inst of results) {
20473
- inst.takeSnapshot?.(snapshotRelations && Object.keys(snapshotRelations).length > 0 ? snapshotRelations : undefined);
20474
- }
20754
+ Ad4mModel.takeSnapshots(results, query.include);
20475
20755
  return { results, totalCount: result.totalCount };
20476
20756
  }
20477
20757
  /**
@@ -20537,13 +20817,7 @@ class Ad4mModel {
20537
20817
  const instances = result.instances.map((json) => {
20538
20818
  return jsonToModelInstance(this, perspective, json, query.include, query.properties);
20539
20819
  });
20540
- // Take snapshots for dirty tracking (exclude $-prefixed projection keys)
20541
- const snapshotRelations = query.include
20542
- ? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith('$')))
20543
- : undefined;
20544
- for (const inst of instances) {
20545
- inst.takeSnapshot(snapshotRelations && Object.keys(snapshotRelations).length > 0 ? snapshotRelations : undefined);
20546
- }
20820
+ Ad4mModel.takeSnapshots(instances, query.include);
20547
20821
  return {
20548
20822
  results: instances,
20549
20823
  totalCount: result.totalCount,
@@ -21688,6 +21962,14 @@ class Ad4mClient {
21688
21962
  onAuthFailed(callback) {
21689
21963
  return __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f").onAuthFailed(callback);
21690
21964
  }
21965
+ /**
21966
+ * Reconnect now if the connection to the executor dropped and the client is
21967
+ * waiting out its backoff: for a host that knows the executor is back (it
21968
+ * restarted it, or the device woke). A no-op while connected or connecting.
21969
+ */
21970
+ reconnectNow() {
21971
+ __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f").reconnectNow();
21972
+ }
21691
21973
  /** Close all event connections and clear in-memory caches */
21692
21974
  close() {
21693
21975
  __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f").clearByDidCache();
@@ -21839,13 +22121,13 @@ class LanguageLanguageInput {
21839
22121
  * const runs = await InterpretationRun.findAll(perspective);
21840
22122
  * const configs = await AutoProcessorConfig.findAll(perspective);
21841
22123
  */
21842
- var __decorate$3 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22124
+ var __decorate$4 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
21843
22125
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
21844
22126
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21845
22127
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
21846
22128
  return c > 3 && r && Object.defineProperty(target, key, r), r;
21847
22129
  };
21848
- var __metadata$3 = (undefined && undefined.__metadata) || function (k, v) {
22130
+ var __metadata$4 = (undefined && undefined.__metadata) || function (k, v) {
21849
22131
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
21850
22132
  };
21851
22133
  // ── AutoProcessorConfig ─────────────────────────────────────────────────────
@@ -21886,71 +22168,71 @@ exports.AutoProcessorConfig = class AutoProcessorConfig extends Ad4mModel {
21886
22168
  // `batchMax` + `claimTtlMs` — the Rust SDNA takes the same shape.
21887
22169
  }
21888
22170
  };
21889
- __decorate$3([
22171
+ __decorate$4([
21890
22172
  Property({ through: "ad4m://processor_id", required: true, identity: true }),
21891
- __metadata$3("design:type", String)
22173
+ __metadata$4("design:type", String)
21892
22174
  ], exports.AutoProcessorConfig.prototype, "processorId", void 0);
21893
- __decorate$3([
22175
+ __decorate$4([
21894
22176
  Property({ through: "ad4m://source_scope_query", required: true }),
21895
- __metadata$3("design:type", String)
22177
+ __metadata$4("design:type", String)
21896
22178
  ], exports.AutoProcessorConfig.prototype, "sourceScopeQuery", void 0);
21897
- __decorate$3([
22179
+ __decorate$4([
21898
22180
  Optional({ through: "ad4m://base_prefix" }),
21899
- __metadata$3("design:type", String)
22181
+ __metadata$4("design:type", String)
21900
22182
  ], exports.AutoProcessorConfig.prototype, "basePrefix", void 0);
21901
- __decorate$3([
22183
+ __decorate$4([
21902
22184
  HasMany({ through: "ad4m://interpretation_class", datatype: "xsd:string" }),
21903
- __metadata$3("design:type", Array)
22185
+ __metadata$4("design:type", Array)
21904
22186
  ], exports.AutoProcessorConfig.prototype, "interpretationClasses", void 0);
21905
- __decorate$3([
22187
+ __decorate$4([
21906
22188
  HasMany({ through: "ad4m://flow", datatype: "xsd:string" }),
21907
- __metadata$3("design:type", Array)
22189
+ __metadata$4("design:type", Array)
21908
22190
  ], exports.AutoProcessorConfig.prototype, "flows", void 0);
21909
- __decorate$3([
22191
+ __decorate$4([
21910
22192
  Property({ through: "ad4m://debounce_ms", required: true }),
21911
- __metadata$3("design:type", String)
22193
+ __metadata$4("design:type", String)
21912
22194
  ], exports.AutoProcessorConfig.prototype, "debounceMs", void 0);
21913
- __decorate$3([
22195
+ __decorate$4([
21914
22196
  Optional({ through: "ad4m://batch_min" }),
21915
- __metadata$3("design:type", String)
22197
+ __metadata$4("design:type", String)
21916
22198
  ], exports.AutoProcessorConfig.prototype, "batchMin", void 0);
21917
- __decorate$3([
22199
+ __decorate$4([
21918
22200
  Property({ through: "ad4m://batch_max", required: true }),
21919
- __metadata$3("design:type", String)
22201
+ __metadata$4("design:type", String)
21920
22202
  ], exports.AutoProcessorConfig.prototype, "batchMax", void 0);
21921
- __decorate$3([
22203
+ __decorate$4([
21922
22204
  Optional({ through: "ad4m://max_wait_ms" }),
21923
- __metadata$3("design:type", String)
22205
+ __metadata$4("design:type", String)
21924
22206
  ], exports.AutoProcessorConfig.prototype, "maxWaitMs", void 0);
21925
- __decorate$3([
22207
+ __decorate$4([
21926
22208
  Property({ through: "ad4m://claim_ttl_ms", required: true }),
21927
- __metadata$3("design:type", String)
22209
+ __metadata$4("design:type", String)
21928
22210
  ], exports.AutoProcessorConfig.prototype, "claimTtlMs", void 0);
21929
- __decorate$3([
22211
+ __decorate$4([
21930
22212
  Optional({ through: "ad4m://source_window_ms" }),
21931
- __metadata$3("design:type", String)
22213
+ __metadata$4("design:type", String)
21932
22214
  ], exports.AutoProcessorConfig.prototype, "sourceWindowMs", void 0);
21933
- __decorate$3([
22215
+ __decorate$4([
21934
22216
  Optional({ through: "ad4m://dedup_strategy" }),
21935
- __metadata$3("design:type", String)
22217
+ __metadata$4("design:type", String)
21936
22218
  ], exports.AutoProcessorConfig.prototype, "dedupStrategy", void 0);
21937
- __decorate$3([
22219
+ __decorate$4([
21938
22220
  Optional({ through: "ad4m://existing_scope" }),
21939
- __metadata$3("design:type", String)
22221
+ __metadata$4("design:type", String)
21940
22222
  ], exports.AutoProcessorConfig.prototype, "existingScope", void 0);
21941
- __decorate$3([
22223
+ __decorate$4([
21942
22224
  Optional({ through: "ad4m://mint_scope" }),
21943
- __metadata$3("design:type", String)
22225
+ __metadata$4("design:type", String)
21944
22226
  ], exports.AutoProcessorConfig.prototype, "mintScope", void 0);
21945
- __decorate$3([
22227
+ __decorate$4([
21946
22228
  Optional({ through: "ad4m://max_tool_calls" }),
21947
- __metadata$3("design:type", String)
22229
+ __metadata$4("design:type", String)
21948
22230
  ], exports.AutoProcessorConfig.prototype, "maxToolCalls", void 0);
21949
- __decorate$3([
22231
+ __decorate$4([
21950
22232
  Optional({ through: "ad4m://emit_debug_events", resolveLanguage: "literal" }),
21951
- __metadata$3("design:type", String)
22233
+ __metadata$4("design:type", String)
21952
22234
  ], exports.AutoProcessorConfig.prototype, "emitDebugEvents", void 0);
21953
- exports.AutoProcessorConfig = __decorate$3([
22235
+ exports.AutoProcessorConfig = __decorate$4([
21954
22236
  Model$1({ name: "AutoProcessor" })
21955
22237
  ], exports.AutoProcessorConfig);
21956
22238
  // ── InterpretationRun ───────────────────────────────────────────────────────
@@ -21974,39 +22256,39 @@ exports.InterpretationRun = class InterpretationRun extends Ad4mModel {
21974
22256
  this.sources = [];
21975
22257
  }
21976
22258
  };
21977
- __decorate$3([
22259
+ __decorate$4([
21978
22260
  Property({ through: "ad4m://interp/run_id", required: true, identity: true }),
21979
- __metadata$3("design:type", String)
22261
+ __metadata$4("design:type", String)
21980
22262
  ], exports.InterpretationRun.prototype, "runId", void 0);
21981
- __decorate$3([
22263
+ __decorate$4([
21982
22264
  Optional({ through: "ad4m://interp/model" }),
21983
- __metadata$3("design:type", String)
22265
+ __metadata$4("design:type", String)
21984
22266
  ], exports.InterpretationRun.prototype, "model", void 0);
21985
- __decorate$3([
22267
+ __decorate$4([
21986
22268
  Optional({ through: "ad4m://interp/prompt_version" }),
21987
- __metadata$3("design:type", String)
22269
+ __metadata$4("design:type", String)
21988
22270
  ], exports.InterpretationRun.prototype, "promptVersion", void 0);
21989
- __decorate$3([
22271
+ __decorate$4([
21990
22272
  Optional({ through: "ad4m://interp/ran_at" }),
21991
- __metadata$3("design:type", String)
22273
+ __metadata$4("design:type", String)
21992
22274
  ], exports.InterpretationRun.prototype, "ranAt", void 0);
21993
- __decorate$3([
22275
+ __decorate$4([
21994
22276
  Optional({ through: "ad4m://interp/processor" }),
21995
- __metadata$3("design:type", String)
22277
+ __metadata$4("design:type", String)
21996
22278
  ], exports.InterpretationRun.prototype, "processor", void 0);
21997
- __decorate$3([
22279
+ __decorate$4([
21998
22280
  HasMany({ through: "ad4m://interp/sources", datatype: "xsd:string" }),
21999
- __metadata$3("design:type", Array)
22281
+ __metadata$4("design:type", Array)
22000
22282
  ], exports.InterpretationRun.prototype, "sources", void 0);
22001
- __decorate$3([
22283
+ __decorate$4([
22002
22284
  Optional({ through: "ad4m://interp/debug_prompt", resolveLanguage: "literal" }),
22003
- __metadata$3("design:type", String)
22285
+ __metadata$4("design:type", String)
22004
22286
  ], exports.InterpretationRun.prototype, "debugPrompt", void 0);
22005
- __decorate$3([
22287
+ __decorate$4([
22006
22288
  Optional({ through: "ad4m://interp/debug_response", resolveLanguage: "literal" }),
22007
- __metadata$3("design:type", String)
22289
+ __metadata$4("design:type", String)
22008
22290
  ], exports.InterpretationRun.prototype, "debugResponse", void 0);
22009
- exports.InterpretationRun = __decorate$3([
22291
+ exports.InterpretationRun = __decorate$4([
22010
22292
  Model$1({ name: "InterpretationRun" })
22011
22293
  ], exports.InterpretationRun);
22012
22294
  // ── InterpretationOverlay ───────────────────────────────────────────────────
@@ -22036,15 +22318,15 @@ exports.InterpretationOverlay = class InterpretationOverlay extends Ad4mModel {
22036
22318
  this.kind = "";
22037
22319
  }
22038
22320
  };
22039
- __decorate$3([
22321
+ __decorate$4([
22040
22322
  Property({ through: "ad4m://interp/kind", required: true }),
22041
- __metadata$3("design:type", String)
22323
+ __metadata$4("design:type", String)
22042
22324
  ], exports.InterpretationOverlay.prototype, "kind", void 0);
22043
- __decorate$3([
22325
+ __decorate$4([
22044
22326
  Optional({ through: "ad4m://interp/run" }),
22045
- __metadata$3("design:type", String)
22327
+ __metadata$4("design:type", String)
22046
22328
  ], exports.InterpretationOverlay.prototype, "run", void 0);
22047
- exports.InterpretationOverlay = __decorate$3([
22329
+ exports.InterpretationOverlay = __decorate$4([
22048
22330
  Model$1({ name: "InterpretationOverlay" })
22049
22331
  ], exports.InterpretationOverlay);
22050
22332
 
@@ -22068,13 +22350,13 @@ exports.InterpretationOverlay = __decorate$3([
22068
22350
  * - the SDNA-parity test locks TS/Rust drift against
22069
22351
  * `rust-executor/src/perspectives/hardwired_sdna/flow_transition_proposal.json`.
22070
22352
  */
22071
- var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22353
+ var __decorate$3 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22072
22354
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22073
22355
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22074
22356
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22075
22357
  return c > 3 && r && Object.defineProperty(target, key, r), r;
22076
22358
  };
22077
- var __metadata$2 = (undefined && undefined.__metadata) || function (k, v) {
22359
+ var __metadata$3 = (undefined && undefined.__metadata) || function (k, v) {
22078
22360
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22079
22361
  };
22080
22362
  /**
@@ -22181,55 +22463,55 @@ exports.FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel
22181
22463
  // of the proposal's own links (all written together during create_subject).
22182
22464
  }
22183
22465
  };
22184
- __decorate$2([
22466
+ __decorate$3([
22185
22467
  Property({ through: "ad4m://flow/instance", required: true, identity: true }),
22186
- __metadata$2("design:type", String)
22468
+ __metadata$3("design:type", String)
22187
22469
  ], exports.FlowTransitionProposal.prototype, "flowInstance", void 0);
22188
- __decorate$2([
22470
+ __decorate$3([
22189
22471
  Property({ through: "ad4m://flow/from_state", required: true }),
22190
- __metadata$2("design:type", String)
22472
+ __metadata$3("design:type", String)
22191
22473
  ], exports.FlowTransitionProposal.prototype, "fromState", void 0);
22192
- __decorate$2([
22474
+ __decorate$3([
22193
22475
  Property({ through: "ad4m://flow/to_state", required: true }),
22194
- __metadata$2("design:type", String)
22476
+ __metadata$3("design:type", String)
22195
22477
  ], exports.FlowTransitionProposal.prototype, "toState", void 0);
22196
- __decorate$2([
22478
+ __decorate$3([
22197
22479
  Property({ through: "ad4m://flow/proposer", required: true, getter: PROPOSER_GETTER, datatype: "xsd:string" }),
22198
- __metadata$2("design:type", String)
22480
+ __metadata$3("design:type", String)
22199
22481
  ], exports.FlowTransitionProposal.prototype, "proposer", void 0);
22200
- __decorate$2([
22482
+ __decorate$3([
22201
22483
  HasMany({ through: "ad4m://flow/evidence", datatype: "xsd:string" }),
22202
- __metadata$2("design:type", Array)
22484
+ __metadata$3("design:type", Array)
22203
22485
  ], exports.FlowTransitionProposal.prototype, "evidence", void 0);
22204
- __decorate$2([
22486
+ __decorate$3([
22205
22487
  Property({ through: "ad4m://flow/evidence_hashes", required: true }),
22206
- __metadata$2("design:type", String)
22488
+ __metadata$3("design:type", String)
22207
22489
  ], exports.FlowTransitionProposal.prototype, "evidenceHashes", void 0);
22208
- __decorate$2([
22490
+ __decorate$3([
22209
22491
  HasMany({ through: "ad4m://flow/output", datatype: "xsd:string" }),
22210
- __metadata$2("design:type", Array)
22492
+ __metadata$3("design:type", Array)
22211
22493
  ], exports.FlowTransitionProposal.prototype, "outputs", void 0);
22212
- __decorate$2([
22494
+ __decorate$3([
22213
22495
  Property({ through: "ad4m://flow/outputs_hash" }),
22214
- __metadata$2("design:type", String)
22496
+ __metadata$3("design:type", String)
22215
22497
  ], exports.FlowTransitionProposal.prototype, "outputsHash", void 0);
22216
- __decorate$2([
22498
+ __decorate$3([
22217
22499
  Property({ through: "ad4m://flow/nonce" }),
22218
- __metadata$2("design:type", String)
22500
+ __metadata$3("design:type", String)
22219
22501
  ], exports.FlowTransitionProposal.prototype, "nonce", void 0);
22220
- __decorate$2([
22502
+ __decorate$3([
22221
22503
  Optional({ through: "ad4m://flow/run_uri" }),
22222
- __metadata$2("design:type", String)
22504
+ __metadata$3("design:type", String)
22223
22505
  ], exports.FlowTransitionProposal.prototype, "runUri", void 0);
22224
- __decorate$2([
22506
+ __decorate$3([
22225
22507
  Optional({ through: "ad4m://flow/rationale" }),
22226
- __metadata$2("design:type", String)
22508
+ __metadata$3("design:type", String)
22227
22509
  ], exports.FlowTransitionProposal.prototype, "rationale", void 0);
22228
- __decorate$2([
22510
+ __decorate$3([
22229
22511
  HasMany({ through: "ad4m://acceptedBy", getter: ACCEPTED_BY_GETTER, readOnly: true }),
22230
- __metadata$2("design:type", Array)
22512
+ __metadata$3("design:type", Array)
22231
22513
  ], exports.FlowTransitionProposal.prototype, "acceptedBy", void 0);
22232
- exports.FlowTransitionProposal = __decorate$2([
22514
+ exports.FlowTransitionProposal = __decorate$3([
22233
22515
  Model$1({ name: "FlowTransitionProposal" })
22234
22516
  ], exports.FlowTransitionProposal);
22235
22517
  // ── FlowInstanceRecord ──────────────────────────────────────────────────────
@@ -22289,25 +22571,25 @@ exports.FlowInstanceRecord = class FlowInstanceRecord extends Ad4mModel {
22289
22571
  // of the instance's own links (all written together during `mint_flow_instance`).
22290
22572
  }
22291
22573
  };
22292
- __decorate$2([
22574
+ __decorate$3([
22293
22575
  Property({ through: "ad4m://flow/flow_uri", required: true, identity: true }),
22294
- __metadata$2("design:type", String)
22576
+ __metadata$3("design:type", String)
22295
22577
  ], exports.FlowInstanceRecord.prototype, "flowUri", void 0);
22296
- __decorate$2([
22578
+ __decorate$3([
22297
22579
  Property({ through: "ad4m://flow/base", required: true }),
22298
- __metadata$2("design:type", String)
22580
+ __metadata$3("design:type", String)
22299
22581
  ], exports.FlowInstanceRecord.prototype, "subject", void 0);
22300
- exports.FlowInstanceRecord = __decorate$2([
22582
+ exports.FlowInstanceRecord = __decorate$3([
22301
22583
  Model$1({ name: "FlowInstance" })
22302
22584
  ], exports.FlowInstanceRecord);
22303
22585
 
22304
- var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22586
+ var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22305
22587
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22306
22588
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22307
22589
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22308
22590
  return c > 3 && r && Object.defineProperty(target, key, r), r;
22309
22591
  };
22310
- var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22592
+ var __metadata$2 = (undefined && undefined.__metadata) || function (k, v) {
22311
22593
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22312
22594
  };
22313
22595
  /**
@@ -22333,6 +22615,10 @@ var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22333
22615
  * reads it by its URI, `ad4m://TextContent`, so a perspective never stores it
22334
22616
  * and an app class named `TextContent` does not replace it. `register()` on
22335
22617
  * it writes nothing.
22618
+ *
22619
+ * The waker's mention subscription (`get_mention_waker_config`) reads it for
22620
+ * the agent's names in the text. Mention links it reads through
22621
+ * {@link Mentioning}, with text or without.
22336
22622
  */
22337
22623
  exports.TextContent = class TextContent extends Ad4mModel {
22338
22624
  constructor() {
@@ -22343,14 +22629,70 @@ exports.TextContent = class TextContent extends Ad4mModel {
22343
22629
  };
22344
22630
  /** The URI the executor reads it by. */
22345
22631
  exports.TextContent.builtinUri = "ad4m://TextContent";
22346
- __decorate$1([
22632
+ __decorate$2([
22347
22633
  Property({ through: "ad4m://text" }),
22348
- __metadata$1("design:type", String)
22634
+ __metadata$2("design:type", String)
22349
22635
  ], exports.TextContent.prototype, "text", void 0);
22350
- exports.TextContent = __decorate$1([
22636
+ exports.TextContent = __decorate$2([
22351
22637
  Model$1({ name: "TextContent", abstract: true })
22352
22638
  ], exports.TextContent);
22353
22639
 
22640
+ var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22641
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22642
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22643
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22644
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
22645
+ };
22646
+ var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22647
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22648
+ };
22649
+ /**
22650
+ * The built-in abstract class `Mentioning { mentions }`: a record that
22651
+ * mentions agents — a post, a message, a block of a document. `mentions` is
22652
+ * a relation to their DIDs.
22653
+ *
22654
+ * Querying it reads every class that has a relation named `mentions`, or one
22655
+ * aliased to `mentions`, under any predicate, whether or not the class has
22656
+ * text. A class whose relation has another name aliases it:
22657
+ *
22658
+ * ```typescript
22659
+ * @Model({ name: "Note", implements: [Mentioning] })
22660
+ * class Note extends Ad4mModel {
22661
+ * @HasMany({ through: "app://cc", alias: { Mentioning: "mentions" } })
22662
+ * cc: string[] = [];
22663
+ * }
22664
+ *
22665
+ * const mentioningMe = await Mentioning.findAll(perspective, { where: { mentions: myDid } });
22666
+ * ```
22667
+ *
22668
+ * The waker's mention subscription (`get_mention_waker_config`) reads it: a
22669
+ * record whose `mentions` links the agent's DID, in a link another agent
22670
+ * wrote, wakes the agent whatever its text says. Names in text it reads
22671
+ * through {@link TextContent}.
22672
+ *
22673
+ * Built in: the executor declares it (mirrors
22674
+ * `rust-executor/src/perspectives/hardwired_sdna/mentioning.json`) and reads
22675
+ * it by its URI, `ad4m://Mentioning`, so a perspective never stores it and an
22676
+ * app class named `Mentioning` does not replace it. `register()` on it writes
22677
+ * nothing.
22678
+ */
22679
+ exports.Mentioning = class Mentioning extends Ad4mModel {
22680
+ constructor() {
22681
+ super(...arguments);
22682
+ /** The agents (DIDs) the record mentions. */
22683
+ this.mentions = [];
22684
+ }
22685
+ };
22686
+ /** The URI the executor reads it by. */
22687
+ exports.Mentioning.builtinUri = "ad4m://Mentioning";
22688
+ __decorate$1([
22689
+ HasMany({ through: "ad4m://mentions" }),
22690
+ __metadata$1("design:type", Array)
22691
+ ], exports.Mentioning.prototype, "mentions", void 0);
22692
+ exports.Mentioning = __decorate$1([
22693
+ Model$1({ name: "Mentioning", abstract: true })
22694
+ ], exports.Mentioning);
22695
+
22354
22696
  var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22355
22697
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22356
22698
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -22999,6 +23341,9 @@ function parseLitBoolean(val) {
22999
23341
  * module (`plugins/ad4m/wakerSubscriptionManager.ts`) rather than carrying its
23000
23342
  * own copy. Any behaviour change belongs here.
23001
23343
  */
23344
+ /** The built-in `Container` (`Container.builtinUri`; not imported, so the
23345
+ * plugin bundle does not pull in the model layer). */
23346
+ const CONTAINER = "ad4m://Container";
23002
23347
  /** A letter, combining mark, digit or underscore: what a term must not touch. */
23003
23348
  const WORD_CHAR = "[\\p{L}\\p{M}\\p{N}_]";
23004
23349
  /**
@@ -23028,14 +23373,6 @@ const BREAKING_TAG = /^<\/?(?:p|div|br|hr|li|ul|ol|h[1-6]|blockquote|pre|tr|td|t
23028
23373
  */
23029
23374
  const ATTRIBUTES = new RegExp(ATTRIBUTE, "g");
23030
23375
  const MENTION_TARGET = /^\s+(?:href|data-id|data-did)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))$/i;
23031
- /**
23032
- * How much of a record's text the word check reads. Dropping markup costs time
23033
- * quadratic in a run of unclosed `<script>`, `<style>` or `<!--` openers, so a
23034
- * very long text could hold the event loop for seconds, and a row that holds
23035
- * no term is checked again on every result while it is in the window. A term
23036
- * past this many characters does not wake.
23037
- */
23038
- const MENTION_TEXT_LIMIT = 16384;
23039
23376
  const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
23040
23377
  function decodeEntities(s) {
23041
23378
  return s.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi, (whole, ref) => {
@@ -23069,6 +23406,14 @@ function readableParts(text) {
23069
23406
  });
23070
23407
  return { visible: decodeEntities(visible), targets };
23071
23408
  }
23409
+ /**
23410
+ * How much of a record's text the word check reads. Dropping markup costs time
23411
+ * quadratic in a run of unclosed `<script>`, `<style>` or `<!--` openers, so a
23412
+ * very long text could hold the event loop for seconds, and a row that holds
23413
+ * no term is checked again on every result while it is in the window. A term
23414
+ * past this many characters does not wake.
23415
+ */
23416
+ const MENTION_TEXT_LIMIT = 16384;
23072
23417
  /**
23073
23418
  * Whether `text` holds one of `terms` as a whole word, case-insensitively:
23074
23419
  * "Data" is in "hi Data!", "@data" and "Data's turn", not in "metadata" or
@@ -23083,7 +23428,9 @@ function readableParts(text) {
23083
23428
  * is how a mention by DID is found when the DID is not in the visible text.
23084
23429
  *
23085
23430
  * The mention query's `contains` matches substrings (model query has no word
23086
- * match); this is the check that keeps "data" from waking on "metadata".
23431
+ * match); this is the check that keeps "data" from waking on "metadata" when
23432
+ * a record is found through its text alone ({@link mentionOf}).
23433
+ *
23087
23434
  * It reads the first {@link MENTION_TEXT_LIMIT} characters only.
23088
23435
  */
23089
23436
  function holdsAWholeWordTerm(text, terms) {
@@ -23097,9 +23444,95 @@ function holdsAWholeWordTerm(text, terms) {
23097
23444
  return new RegExp(`(?<!${WORD_CHAR})${escaped}(?!${WORD_CHAR})`, "iu").test(visible);
23098
23445
  });
23099
23446
  }
23100
- /** The built-in `Container` (`Container.builtinUri`; not imported, so the
23101
- * plugin bundle does not pull in the model layer). */
23102
- const CONTAINER = "ad4m://Container";
23447
+ /** The provenance {@link MentionMessage} carries, from one link. */
23448
+ function provenanceOf(link, via) {
23449
+ const provenance = {
23450
+ verified: link?.proof?.valid === true,
23451
+ via,
23452
+ };
23453
+ if (typeof link?.author === "string")
23454
+ provenance.author = link.author;
23455
+ if (typeof link?.timestamp === "string")
23456
+ provenance.timestamp = link.timestamp;
23457
+ return provenance;
23458
+ }
23459
+ /** The links a model row carries for `key` under `__links`, oldest first. */
23460
+ function rowLinks(row, key) {
23461
+ const links = row?.__links?.[key];
23462
+ return Array.isArray(links) ? links : [];
23463
+ }
23464
+ /** `uri` URI-decoded, or as it is when it is not valid percent-encoding. */
23465
+ function decoded(uri) {
23466
+ try {
23467
+ return decodeURIComponent(uri);
23468
+ }
23469
+ catch {
23470
+ return uri;
23471
+ }
23472
+ }
23473
+ /**
23474
+ * The text a link's target holds, read as the executor reads a string property
23475
+ * (`parse_literal_value`): `literal:string:` decoded, `literal:json:` parsed (a signed
23476
+ * expression to its `data`), any other URI as it is. `undefined` when that is not a string.
23477
+ */
23478
+ function textOf(target) {
23479
+ if (typeof target !== "string")
23480
+ return undefined;
23481
+ if (!target.startsWith("literal:"))
23482
+ return target;
23483
+ const body = target.slice("literal:".length);
23484
+ if (body.startsWith("string:"))
23485
+ return decoded(body.slice("string:".length));
23486
+ if (body.startsWith("json:")) {
23487
+ const json = decoded(body.slice("json:".length));
23488
+ let value;
23489
+ try {
23490
+ value = JSON.parse(json);
23491
+ }
23492
+ catch {
23493
+ return json;
23494
+ }
23495
+ if (value && typeof value === "object" && "data" in value && "author" in value && "proof" in value) {
23496
+ value = value.data;
23497
+ }
23498
+ return typeof value === "string" ? value : undefined;
23499
+ }
23500
+ if (/^(?:number|boolean):/.test(body))
23501
+ return undefined;
23502
+ return target;
23503
+ }
23504
+ /**
23505
+ * Whether a row of one of the mention subscription's two model queries mentions the
23506
+ * subscription's agent, and the provenance of the link it does so in; `null` when it does not.
23507
+ *
23508
+ * - A row of the query over Mentioning: a verified link to the agent's DID that another agent
23509
+ * wrote, in the row's `__links.mentions`. It wakes whatever the record's text says, or
23510
+ * whether it has any: WE's chip label may run into the next word ("@Datai have…"), and a WE
23511
+ * post's mention sits on its root, which has no text. Its provenance is that link's (the
23512
+ * newest such).
23513
+ * - A row of the query over TextContent: the query matched a substring, so the text must hold
23514
+ * a term as a whole word ({@link holdsAWholeWordTerm}), and so must the text of a verified
23515
+ * link another agent wrote, in `__links.text`. Its provenance is that link's (the newest
23516
+ * such). The row's `text` is the newest text link's, whoever wrote it, so it does not say
23517
+ * whose words they are.
23518
+ *
23519
+ * `via` says which it was. A record both queries find wakes once, through the query that
23520
+ * reports it first ({@link WakerSubscriptionManager}).
23521
+ */
23522
+ function mentionOf(row, sub) {
23523
+ const did = sub.did;
23524
+ const byOthers = (links) => links.filter((l) => typeof l.author === "string" && l.author !== did);
23525
+ const linked = byOthers(rowLinks(row, "mentions")).filter((l) => l.data?.target === did && l.proof?.valid === true);
23526
+ if (did && linked.length)
23527
+ return provenanceOf(linked[linked.length - 1], "mentions");
23528
+ const terms = sub.terms ?? [];
23529
+ const names = (text) => typeof text === "string" && holdsAWholeWordTerm(text, terms);
23530
+ const text = Array.isArray(row?.text) ? row.text.join(" ") : row?.text;
23531
+ if (!names(text))
23532
+ return null;
23533
+ const naming = byOthers(rowLinks(row, "text")).filter((l) => l.proof?.valid === true && names(textOf(l.data?.target)));
23534
+ return naming.length ? provenanceOf(naming[naming.length - 1], "text") : null;
23535
+ }
23103
23536
  /**
23104
23537
  * Add a short cause hint to known subscription failures.
23105
23538
  * The executor needs its main key to register a live query; on a restarted
@@ -23145,11 +23578,23 @@ async function withTimeout(promise, ms, message) {
23145
23578
  }
23146
23579
  class WakerSubscriptionManager {
23147
23580
  constructor(options) {
23581
+ /** Per subscription its proxies: one, or a mention subscription's text and mention queries. */
23148
23582
  this.proxies = new Map();
23149
23583
  this.activeSubscriptions = new Map();
23150
23584
  /** Subscriptions the executor rejected, waiting to be re-attempted. */
23151
23585
  this.pendingSubscriptions = new Map();
23152
23586
  this.retryTimer = null;
23587
+ /** Re-attempt rounds in a row that left something pending, for the backoff. */
23588
+ this.retryRounds = 0;
23589
+ /**
23590
+ * Subscriptions that were active until one of their live queries lost its
23591
+ * executor subscription (a reconnect, a failed resync) and failed to open it
23592
+ * again, with the proxies still re-opening. The query retries on its own,
23593
+ * with backoff, so the manager does not subscribe them again; it reports
23594
+ * them as pending instead of active until every proxy is open again, and
23595
+ * keeps persisting them so a restart restores them (#1595).
23596
+ */
23597
+ this.reopening = new Map();
23153
23598
  /**
23154
23599
  * Cancellation tokens for in-flight `subscribe()` calls.
23155
23600
  *
@@ -23189,6 +23634,7 @@ class WakerSubscriptionManager {
23189
23634
  this.QuerySubscriptionProxyCtor = options.QuerySubscriptionProxy ?? null;
23190
23635
  this.previousSeenMessages = options.previousSeenMessages ?? {};
23191
23636
  this.retryPendingMs = options.retryPendingMs ?? 30000;
23637
+ this.maxRetryPendingMs = Math.max(this.retryPendingMs, options.maxRetryPendingMs ?? 300000);
23192
23638
  this.subscribeTimeoutMs = options.subscribeTimeoutMs ?? 15000;
23193
23639
  this.retryWakeMs = options.retryWakeMs ?? 5000;
23194
23640
  }
@@ -23207,28 +23653,51 @@ class WakerSubscriptionManager {
23207
23653
  * If a subscription with the same id already exists, it is disposed first.
23208
23654
  */
23209
23655
  async subscribe(sub) {
23210
- // Dispose existing subscription with same id if any
23211
- this.dispose(sub.id, false);
23656
+ // Dispose existing subscription with same id if any. Not `dispose()`: a
23657
+ // re-attempt must not start the backoff over.
23658
+ this.release(sub.id, false);
23212
23659
  const token = this.beginAttempt(sub.id);
23213
23660
  if (!this.QuerySubscriptionProxyCtor) {
23214
23661
  throw new Error("WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options");
23215
23662
  }
23216
23663
  const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;
23217
- if (sub.type === "mention" && sub.className && !sub.terms?.length) {
23218
- // Without terms the whole-word check cannot run, and every substring
23219
- // ("metadata" for "data") would wake the agent.
23220
- throw new Error(`Waker subscription ${sub.id}: a mention subscription needs its terms (get_mention_waker_config returns them)`);
23664
+ if (sub.type === "mention" &&
23665
+ (!sub.className || !sub.terms?.length || !sub.did || !sub.mentionQuery || !sub.mentionClass)) {
23666
+ // Without terms the whole-word check cannot run, so every substring
23667
+ // ("metadata" for "data") would wake the agent; without the DID no link
23668
+ // can be told to be someone else's; without the mention query a mention
23669
+ // link on a record with no text (a WE post's root) never wakes it.
23670
+ throw new Error(`Waker subscription ${sub.id}: a mention subscription needs its TextContent class, terms, DID and Mentioning query (get_mention_waker_config returns them)`);
23221
23671
  }
23222
23672
  this.logger.info(`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`);
23223
23673
  this.logger.info(`[waker] ${sub.id}: ${sub.className ? `model query over ${sub.className}` : "SPARQL query"}:\n${sub.query}`);
23674
+ if (sub.mentionQuery) {
23675
+ this.logger.info(`[waker] ${sub.id}: model query over ${sub.mentionClass}:\n${sub.mentionQuery}`);
23676
+ }
23224
23677
  const proxy = sub.className
23225
23678
  ? new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient, sub.className)
23226
23679
  : new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
23680
+ const mentionProxy = sub.mentionQuery
23681
+ ? new QuerySubscriptionProxy(sub.perspective, sub.mentionQuery, this.perspectiveClient, sub.mentionClass)
23682
+ : undefined;
23683
+ const proxies = mentionProxy ? [proxy, mentionProxy] : [proxy];
23684
+ // `cancelOpening`: a handshake given up on must not keep the executor
23685
+ // computing a first result nobody reads; abandoned ones piled up into
23686
+ // hundreds of busy executor threads on staging (#1595).
23687
+ const disposeProxies = () => {
23688
+ for (const p of proxies) {
23689
+ try {
23690
+ p.dispose({ cancelOpening: true });
23691
+ }
23692
+ catch { }
23693
+ }
23694
+ };
23227
23695
  // Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
23228
23696
  // rejects this promise internally when subscribe() fails, and if nobody catches
23229
23697
  // it before the next microtask it crashes the process.
23230
- if (proxy.initialized && typeof proxy.initialized.catch === "function") {
23231
- proxy.initialized.catch(() => { });
23698
+ for (const p of proxies) {
23699
+ if (p.initialized && typeof p.initialized.catch === "function")
23700
+ p.initialized.catch(() => { });
23232
23701
  }
23233
23702
  // One deadline for the whole handshake: `proxy.subscribe()` and the
23234
23703
  // `initialized` promise it resolves share the budget, so a hang in either
@@ -23239,23 +23708,17 @@ class WakerSubscriptionManager {
23239
23708
  ? withTimeout(step, Math.max(0, budgetMs - (Date.now() - startedAt)), `${what} timed out after ${budgetMs}ms`)
23240
23709
  : step;
23241
23710
  try {
23242
- await bounded(proxy.subscribe(), "subscribe handshake");
23711
+ await bounded(Promise.all(proxies.map((p) => p.subscribe())), "subscribe handshake");
23243
23712
  if (this.isStale(sub.id, token)) {
23244
- try {
23245
- proxy.dispose();
23246
- }
23247
- catch { }
23713
+ disposeProxies();
23248
23714
  return;
23249
23715
  }
23250
- await bounded(proxy.initialized, "subscription initialization");
23716
+ await bounded(Promise.all(proxies.map((p) => p.initialized)), "subscription initialization");
23251
23717
  }
23252
23718
  catch (err) {
23253
23719
  const msg = err?.message ?? String(err);
23254
23720
  this.logger.warn(`[waker] ${sub.id}: subscription failed — ${msg}`);
23255
- try {
23256
- proxy.dispose();
23257
- }
23258
- catch { }
23721
+ disposeProxies();
23259
23722
  // A dispose that landed mid-attempt wins: don't re-queue something the
23260
23723
  // caller has since asked us to forget.
23261
23724
  if (this.isStale(sub.id, token))
@@ -23276,17 +23739,16 @@ class WakerSubscriptionManager {
23276
23739
  // turn this into an error result instead of a false "Subscribed" reply.
23277
23740
  throw new Error(`Waker subscription ${sub.id} failed: ${msg}${hintFor(msg)}` +
23278
23741
  (this.retryPendingMs > 0
23279
- ? `. Not listening yet — re-attempting every ${Math.round(this.retryPendingMs / 1000)}s; check ad4m_list_waker_subscriptions.`
23742
+ ? `. Not listening yet — re-attempting within ${Math.round(this.retryCeiling() / 1000)}s, then less often (at most every ${Math.round(this.maxRetryPendingMs / 1000)}s); check ad4m_list_waker_subscriptions.`
23280
23743
  : ""));
23281
23744
  }
23282
23745
  if (this.isStale(sub.id, token)) {
23283
- try {
23284
- proxy.dispose();
23285
- }
23286
- catch { }
23746
+ disposeProxies();
23287
23747
  return;
23288
23748
  }
23289
23749
  this.pendingSubscriptions.delete(sub.id);
23750
+ if (this.pendingSubscriptions.size === 0)
23751
+ this.retryRounds = 0;
23290
23752
  this.logger.info(`[waker] ${sub.id}: subscription initialized successfully`);
23291
23753
  // Seed from persisted seen messages so we don't re-wake after restart
23292
23754
  const restored = Object.prototype.hasOwnProperty.call(this.previousSeenMessages, sub.id);
@@ -23298,8 +23760,9 @@ class WakerSubscriptionManager {
23298
23760
  }
23299
23761
  // `opening` is the result the subscription holds when it opens (`proxy.result`): `onResult`
23300
23762
  // only reports later changes, so this is the one chance to see what was written meanwhile.
23301
- const handleResult = async (result, opening = false) => {
23302
- this.logger.info(`[waker] ${sub.id}: ${opening ? "opening result" : "onResult fired"} — type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);
23763
+ // `of`: the query the result is from, for the log (a mention subscription has two).
23764
+ const handleResult = async (result, opening = false, of = "") => {
23765
+ 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)}`);
23303
23766
  // A model subscription delivers `{ instances }`, SPARQL an array of
23304
23767
  // rows. Anything else (e.g. `false` on a disconnect/reconnect) is
23305
23768
  // ignored.
@@ -23309,26 +23772,25 @@ class WakerSubscriptionManager {
23309
23772
  return;
23310
23773
  }
23311
23774
  if (sub.type === "mention") {
23312
- // For mention subscriptions: track seen record ids.
23313
- // Only wake for records we haven't seen before.
23775
+ // For mention subscriptions: track seen record ids, across both queries, and wake only
23776
+ // for records not seen before, so a record both find wakes once, through the query that
23777
+ // reports it first.
23314
23778
  const currentSeen = this.seenMessages.get(sub.id) ?? new Set();
23315
23779
  const newMessages = [];
23316
- const terms = sub.terms ?? [];
23780
+ const provenance = new Map();
23317
23781
  for (const item of rows) {
23318
- // A SPARQL row names the record as `source`, a model row as `id`.
23319
- const address = sub.className ? item?.id : item?.source;
23782
+ const address = item?.id;
23320
23783
  if (typeof address !== "string" || !address || currentSeen.has(address))
23321
23784
  continue;
23322
- if (terms.length) {
23323
- // The mention query matched a substring; wake only on a whole word.
23324
- const text = Array.isArray(item.text) ? item.text.join(" ") : item.text;
23325
- if (typeof text !== "string" || !holdsAWholeWordTerm(text, terms)) {
23326
- this.logger.debug(`[waker] ${sub.id}: ${address} holds no term as a whole word, skipping`);
23327
- continue;
23328
- }
23785
+ // A mention link as it is; the text, a whole word only.
23786
+ const mention = mentionOf(item, sub);
23787
+ if (!mention) {
23788
+ this.logger.debug(`[waker] ${sub.id}: ${address} has no verified mention link and no term as a whole word, skipping`);
23789
+ continue;
23329
23790
  }
23330
23791
  currentSeen.add(address);
23331
23792
  newMessages.push(address);
23793
+ provenance.set(address, mention);
23332
23794
  }
23333
23795
  if (newMessages.length === 0) {
23334
23796
  this.logger.info(`[waker] ${sub.id}: no new mention among ${rows.length} items, skipping`);
@@ -23353,7 +23815,7 @@ class WakerSubscriptionManager {
23353
23815
  const ancestors = await this.ancestorsOf(sub, msgAddr, parents);
23354
23816
  this.logger.info(`[waker] ${sub.id}: message ${msgAddr} has ${parents.length} parent(s): ${parents.join(", ")}` +
23355
23817
  (ancestors.length ? `; ancestors: ${ancestors.join(", ")}` : ""));
23356
- mentions.push({ address: msgAddr, parents, ancestors });
23818
+ mentions.push({ address: msgAddr, parents, ancestors, ...provenance.get(msgAddr) });
23357
23819
  }
23358
23820
  this.seenMessages.set(sub.id, currentSeen);
23359
23821
  const pending = this.undelivered.get(sub.id) ?? new Map();
@@ -23379,20 +23841,24 @@ class WakerSubscriptionManager {
23379
23841
  }
23380
23842
  };
23381
23843
  proxy.onResult((result) => handleResult(result));
23844
+ mentionProxy?.onResult((result) => handleResult(result, false, " (mention query)"));
23845
+ for (const p of proxies) {
23846
+ p.onStatus?.((status) => this.onReopenStatus(sub, proxies, p, status));
23847
+ }
23382
23848
  if (this.isStale(sub.id, token)) {
23383
- try {
23384
- proxy.dispose();
23385
- }
23386
- catch { }
23849
+ disposeProxies();
23387
23850
  return;
23388
23851
  }
23389
- this.proxies.set(sub.id, proxy);
23852
+ this.proxies.set(sub.id, proxies);
23390
23853
  this.activeSubscriptions.set(sub.id, sub);
23391
23854
  // After a restart this wakes on mentions written while the waker was down; on a new
23392
- // subscription it records the existing ones as history.
23393
- if (proxy.result !== undefined) {
23855
+ // subscription it records the existing ones as history. The mention query's first, so a
23856
+ // record both hold wakes through its mention link.
23857
+ for (const [p, of] of [[mentionProxy, " (mention query)"], [proxy, ""]]) {
23858
+ if (p?.result === undefined)
23859
+ continue;
23394
23860
  try {
23395
- await handleResult(proxy.result, true);
23861
+ await handleResult(p.result, true, of);
23396
23862
  }
23397
23863
  catch (e) {
23398
23864
  this.logger.warn(`[waker] ${sub.id}: reading the opening result failed: ${e?.message ?? e}`);
@@ -23401,6 +23867,51 @@ class WakerSubscriptionManager {
23401
23867
  this.persist();
23402
23868
  this.logger.info(`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`);
23403
23869
  }
23870
+ /**
23871
+ * A proxy of `sub` failed to re-open its live query, or re-opened it after
23872
+ * failing. `sub` counts as active again once none of its proxies is still
23873
+ * re-opening. `proxies` tells a status of a replaced subscription apart.
23874
+ */
23875
+ onReopenStatus(sub, proxies, proxy, status) {
23876
+ if (this.proxies.get(sub.id) !== proxies)
23877
+ return;
23878
+ if (status?.state === "reopening") {
23879
+ const entry = this.reopening.get(sub.id) ?? { sub, proxies: new Set() };
23880
+ entry.proxies.add(proxy);
23881
+ if (!this.reopening.has(sub.id)) {
23882
+ this.reopening.set(sub.id, entry);
23883
+ this.activeSubscriptions.delete(sub.id);
23884
+ this.logger.warn(`[waker] ${sub.id}: live query lost after a reconnect and could not be re-opened (${status.error?.message ?? status.error}); not listening, retrying in ${Math.round((status.retryInMs ?? 0) / 1000)}s`);
23885
+ }
23886
+ return;
23887
+ }
23888
+ if (status?.state !== "open")
23889
+ return;
23890
+ const entry = this.reopening.get(sub.id);
23891
+ if (!entry)
23892
+ return;
23893
+ entry.proxies.delete(proxy);
23894
+ if (entry.proxies.size > 0)
23895
+ return;
23896
+ this.reopening.delete(sub.id);
23897
+ this.activeSubscriptions.set(sub.id, sub);
23898
+ this.logger.info(`[waker] ${sub.id}: live query re-opened, listening again`);
23899
+ // Wakes held back while it was not active go out now, not with the next mention.
23900
+ if (this.undelivered.get(sub.id)?.size)
23901
+ this.scheduleMentionWake(sub, proxy.result, this.debounceMs);
23902
+ }
23903
+ /** The wait before the next re-attempt round: `retryPendingMs` doubled per
23904
+ * round in a row that left something pending, capped at
23905
+ * `maxRetryPendingMs`, and between half and all of that, so wakers of a
23906
+ * restarted executor do not all retry at once. */
23907
+ nextRetryDelay() {
23908
+ const ceiling = this.retryCeiling();
23909
+ return ceiling / 2 + Math.random() * (ceiling / 2);
23910
+ }
23911
+ /** The longest the next re-attempt round waits. */
23912
+ retryCeiling() {
23913
+ return Math.min(this.retryPendingMs * 2 ** this.retryRounds, this.maxRetryPendingMs);
23914
+ }
23404
23915
  /** Arm the re-attempt timer if pending subscriptions are waiting. */
23405
23916
  scheduleRetry() {
23406
23917
  if (this.retryPendingMs <= 0)
@@ -23409,8 +23920,9 @@ class WakerSubscriptionManager {
23409
23920
  return;
23410
23921
  this.retryTimer = setTimeout(() => {
23411
23922
  this.retryTimer = null;
23923
+ this.retryRounds++;
23412
23924
  void this.retryPending();
23413
- }, this.retryPendingMs);
23925
+ }, this.nextRetryDelay());
23414
23926
  if (typeof this.retryTimer.unref === "function")
23415
23927
  this.retryTimer.unref();
23416
23928
  }
@@ -23444,27 +23956,39 @@ class WakerSubscriptionManager {
23444
23956
  }
23445
23957
  }
23446
23958
  }
23447
- /** Subscriptions that were rejected and are waiting to be re-attempted. */
23959
+ /** Subscriptions that are not listening and are being re-attempted: the
23960
+ * ones the executor rejected, and active ones whose live query is
23961
+ * re-opening after a reconnect. */
23448
23962
  getPending() {
23449
- return Array.from(this.pendingSubscriptions.values());
23963
+ return [
23964
+ ...this.pendingSubscriptions.values(),
23965
+ ...Array.from(this.reopening.values(), (entry) => entry.sub),
23966
+ ];
23450
23967
  }
23451
23968
  /**
23452
23969
  * Dispose a single subscription.
23453
23970
  * @param persist — if false, skip calling onPersist (used during batch cleanup).
23454
23971
  */
23455
23972
  dispose(id, persist = true) {
23973
+ this.release(id, persist);
23974
+ if (this.pendingSubscriptions.size === 0)
23975
+ this.retryRounds = 0;
23976
+ }
23977
+ /** Drop everything held for `id`, as `dispose()` does, but leave the
23978
+ * re-attempt backoff as it is. */
23979
+ release(id, persist) {
23456
23980
  // Invalidate any subscribe() for this id that is still awaiting.
23457
23981
  this.generations.set(id, (this.generations.get(id) ?? 0) + 1);
23458
- const proxy = this.proxies.get(id);
23459
- if (proxy) {
23982
+ for (const proxy of this.proxies.get(id) ?? []) {
23460
23983
  try {
23461
- proxy.dispose();
23984
+ proxy.dispose({ cancelOpening: true });
23462
23985
  }
23463
23986
  catch {
23464
23987
  /* ignore */
23465
23988
  }
23466
- this.proxies.delete(id);
23467
23989
  }
23990
+ this.proxies.delete(id);
23991
+ this.reopening.delete(id);
23468
23992
  const timer = this.debounceTimers.get(id);
23469
23993
  if (timer) {
23470
23994
  clearTimeout(timer);
@@ -23537,6 +24061,8 @@ class WakerSubscriptionManager {
23537
24061
  this.dispose(id, false);
23538
24062
  }
23539
24063
  this.pendingSubscriptions.clear();
24064
+ this.reopening.clear();
24065
+ this.retryRounds = 0;
23540
24066
  if (this.retryTimer) {
23541
24067
  clearTimeout(this.retryTimer);
23542
24068
  this.retryTimer = null;
@@ -23596,7 +24122,9 @@ class WakerSubscriptionManager {
23596
24122
  for (const [id, set] of this.delivered) {
23597
24123
  seen[id] = Array.from(set);
23598
24124
  }
23599
- this.onPersist(this.getActive(), seen);
24125
+ // A subscription that is re-opening was enrolled and is coming back: a
24126
+ // restart in the meantime must restore it.
24127
+ this.onPersist([...this.getActive(), ...Array.from(this.reopening.values(), (entry) => entry.sub)], seen);
23600
24128
  }
23601
24129
  }
23602
24130
  }
@@ -24138,6 +24666,8 @@ exports.PerspectiveUnsignedInput = PerspectiveUnsignedInput;
24138
24666
  exports.Property = Property;
24139
24667
  exports.QuerySubscriptionProxy = QuerySubscriptionProxy;
24140
24668
  exports.READ_METHODS = READ_METHODS;
24669
+ exports.REOPEN_BASE_DELAY_MS = REOPEN_BASE_DELAY_MS;
24670
+ exports.REOPEN_MAX_DELAY_MS = REOPEN_MAX_DELAY_MS;
24141
24671
  exports.ReadOnly = ReadOnly;
24142
24672
  exports.Resource = Resource;
24143
24673
  exports.ResourceInput = ResourceInput;
@@ -24212,6 +24742,7 @@ exports.linkExpressionToWire = linkExpressionToWire;
24212
24742
  exports.linkMutationsToWire = linkMutationsToWire;
24213
24743
  exports.literal = literal;
24214
24744
  exports.looksLikeUri = looksLikeUri;
24745
+ exports.mentionOf = mentionOf;
24215
24746
  exports.neighbourhoodExpressionFromWire = neighbourhoodExpressionFromWire;
24216
24747
  exports.normalizeNamespaceString = normalizeNamespaceString;
24217
24748
  exports.normalizeSchemaType = normalizeSchemaType;
@@ -24225,6 +24756,7 @@ exports.parseLitNumber = parseLitNumber;
24225
24756
  exports.parseSparqlCount = parseSparqlCount;
24226
24757
  exports.path = path;
24227
24758
  exports.queryCacheSize = queryCacheSize;
24759
+ exports.reopenDelay = reopenDelay;
24228
24760
  exports.requireSingleParent = requireSingleParent;
24229
24761
  exports.resolveParentPredicate = resolveParentPredicate;
24230
24762
  exports.setCachedResult = setCachedResult;