@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.js CHANGED
@@ -105,6 +105,7 @@ const LONG_METHODS = new Set([
105
105
  "language.publish",
106
106
  "neighbourhood.join",
107
107
  "neighbourhood.publish",
108
+ "perspective.runAgent",
108
109
  "perspective.runInterpretation",
109
110
  "perspective.runInterpretationWithHarness",
110
111
  "runtime.restartHolochain",
@@ -128,6 +129,34 @@ const MAX_RECONNECT_DELAY_MS = 30000;
128
129
  * MAX_WATCH_RETRIES times in a row. */
129
130
  const WATCH_RETRY_DELAY_MS = 1000;
130
131
  const MAX_WATCH_RETRIES = 5;
132
+ /** An open socket sends a ping this often, and must deliver some message
133
+ * (the pong will do) within an interval of the first ping it left
134
+ * unanswered. After a network switch a socket can stay OPEN for minutes with
135
+ * no close event, since no FIN or RST ever arrives; this notices it within
136
+ * two intervals. */
137
+ const PING_INTERVAL_MS = 10000;
138
+ /** The slowest link a socket is given time for. The executor reads a ping
139
+ * only after the frames sent before it, so a ping left unanswered counts as
140
+ * silence only once everything the socket sent before that ping could have
141
+ * crossed this link and PONG_RETURN_MS more have passed, if that takes longer
142
+ * than PING_INTERVAL_MS. Messages that come in meanwhile do not shorten this:
143
+ * they say nothing about how far an upload has got. */
144
+ const SLOWEST_LINK_BYTES_PER_MS = 16; // 16 kB/s
145
+ /** How long a pong gets to come back after its ping could have been read
146
+ * behind a large write. Shorter than PING_INTERVAL_MS, so the few ms a small
147
+ * frame adds before a ping on an idle socket never cost a ping interval. */
148
+ const PONG_RETURN_MS = 5000;
149
+ /** The bytes `text` takes as UTF-8, as a WebSocket text frame sends it. */
150
+ function utf8Length(text) {
151
+ let bytes = text.length;
152
+ for (let i = 0; i < text.length; i++) {
153
+ const unit = text.charCodeAt(i);
154
+ // A surrogate is half of a 4-byte pair: 2 units, 2 extra bytes.
155
+ if (unit >= 0x80)
156
+ bytes += unit < 0x800 || (unit >= 0xd800 && unit <= 0xdfff) ? 1 : 2;
157
+ }
158
+ return bytes;
159
+ }
131
160
  let _idCounter = 0;
132
161
  function nextId() {
133
162
  return String(++_idCounter);
@@ -162,6 +191,14 @@ class ApiClient {
162
191
  this._wsReconnectTimer = null;
163
192
  this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;
164
193
  this._wsPingTimer = null;
194
+ /** When the open socket was first pinged since it last delivered a message; null while none is unanswered. */
195
+ this._wsPingedAt = null;
196
+ /** When that ping could have reached the executor, which reads it only after what the socket sent before it. */
197
+ this._wsPingArrivesBy = 0;
198
+ /** When everything the open socket sent so far could have crossed a SLOWEST_LINK_BYTES_PER_MS link.
199
+ * A message from the socket does not move it back: hearing from the executor says nothing
200
+ * about how much of a large upload has reached it. */
201
+ this._wsSentBy = 0;
165
202
  // The executor sends a socket only the events it asked for (`events.watch`).
166
203
  // What the executor has for the open socket, as sent; a new socket has `{}`.
167
204
  this._watching = '{}';
@@ -171,6 +208,13 @@ class ApiClient {
171
208
  this._watchSent = Promise.resolve();
172
209
  this._watchRetries = 0;
173
210
  this._watchRetryTimer = null;
211
+ this._wakeListening = false;
212
+ /** `online` always; `visibilitychange` only when the page became visible. */
213
+ this._onWake = (event) => {
214
+ if (event.type === 'visibilitychange' && typeof document !== 'undefined' && document.visibilityState !== 'visible')
215
+ return;
216
+ this.reconnectNow();
217
+ };
174
218
  this.baseUrl = baseUrl;
175
219
  this.token = token;
176
220
  this._webSocketImpl = webSocketImpl;
@@ -194,6 +238,9 @@ class ApiClient {
194
238
  return;
195
239
  if (this._authFailed !== null)
196
240
  throw new RpcError(401, this._authFailed);
241
+ // A dial ends any wait for one: a call or subscriber that dials during the backoff
242
+ // leaves no timer behind to swallow the retry after this socket's own drop.
243
+ this._cancelReconnect();
197
244
  const WsImpl = this._webSocketImpl ?? globalThis.WebSocket;
198
245
  const ws = new WsImpl(this._getWsUrl());
199
246
  this._ws = ws;
@@ -218,6 +265,8 @@ class ApiClient {
218
265
  // Only watchApplied() awaits this; a close before open is not an error otherwise.
219
266
  this._wsOpen.catch(() => { });
220
267
  ws.onmessage = (event) => {
268
+ if (this._ws === ws)
269
+ this._wsPingedAt = null;
221
270
  let parsed;
222
271
  try {
223
272
  parsed = JSON.parse(event.data);
@@ -243,7 +292,8 @@ class ApiClient {
243
292
  this._failAuth(rpcError.body);
244
293
  return;
245
294
  }
246
- if (parsed.type === 'pong')
295
+ // A dropped socket's events are not this client's any more: its successor watches again.
296
+ if (parsed.type === 'pong' || this._ws !== ws)
247
297
  return;
248
298
  const perspective = parsed.perspectiveUuid;
249
299
  const regs = this._handlers.get(parsed.type);
@@ -266,14 +316,14 @@ class ApiClient {
266
316
  if (this._ws !== ws)
267
317
  return;
268
318
  this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;
269
- this._startPing();
319
+ this._startPing(ws);
270
320
  // The watch goes out before the queued calls, so the events they cause reach listeners.
271
321
  this._watching = '{}';
272
322
  this._watchRetries = 0;
273
323
  this._flushWatch();
274
324
  for (const pending of this._pendingCalls.values()) {
275
325
  if (!pending.sent) {
276
- ws.send(pending.message);
326
+ this._send(ws, pending.message);
277
327
  pending.sent = true;
278
328
  }
279
329
  }
@@ -324,13 +374,40 @@ class ApiClient {
324
374
  for (const cb of [...this._authFailedCallbacks])
325
375
  callSafely(cb, 'Error in auth-failed callback:', reason);
326
376
  }
327
- _startPing() {
377
+ _startPing(ws) {
328
378
  this._stopPing();
379
+ this._wsPingedAt = null;
380
+ this._wsSentBy = 0;
329
381
  this._wsPingTimer = setInterval(() => {
330
- if (this._ws?.readyState === 1 /* OPEN */) {
331
- this._ws.send(JSON.stringify({ type: 'ping' }));
382
+ if (this._ws !== ws)
383
+ return;
384
+ const ping = JSON.stringify({ type: 'ping' });
385
+ if (this._wsPingedAt === null) {
386
+ this._wsPingedAt = performance.now();
387
+ this._send(ws, ping);
388
+ this._wsPingArrivesBy = this._wsSentBy;
389
+ return;
332
390
  }
333
- }, 30000);
391
+ if (performance.now() >= Math.max(this._wsPingedAt + PING_INTERVAL_MS, this._wsPingArrivesBy + PONG_RETURN_MS)) {
392
+ this._dropSilentSocket(ws);
393
+ return;
394
+ }
395
+ this._send(ws, ping);
396
+ }, PING_INTERVAL_MS);
397
+ }
398
+ /** Send on `ws`, counting how long what the open socket sent could take to cross the slowest link. */
399
+ _send(ws, text) {
400
+ if (this._ws === ws)
401
+ this._wsSentBy = Math.max(this._wsSentBy, performance.now()) + utf8Length(text) / SLOWEST_LINK_BYTES_PER_MS;
402
+ ws.send(text);
403
+ }
404
+ /** The socket answered nothing for a whole ping interval: treat it as
405
+ * closed now. Its close event can take minutes on a dead connection,
406
+ * since the close frame gets no answer either; `_onClose` ignores it then. */
407
+ _dropSilentSocket(ws) {
408
+ console.warn(`WebSocket silent for ${performance.now() - (this._wsPingedAt ?? performance.now())} ms after a ping; reconnecting`);
409
+ this._onClose(ws);
410
+ ws.close();
334
411
  }
335
412
  _stopPing() {
336
413
  if (this._wsPingTimer) {
@@ -345,8 +422,54 @@ class ApiClient {
345
422
  this._wsReconnectDelay = Math.min(this._wsReconnectDelay * 2, MAX_RECONNECT_DELAY_MS);
346
423
  this._wsReconnectTimer = setTimeout(() => {
347
424
  this._wsReconnectTimer = null;
425
+ this._listenForWake(false);
348
426
  this._ensureWs();
349
427
  }, delay);
428
+ this._listenForWake(true);
429
+ }
430
+ /** End the wait for the next dial, if one is pending, without dialling. */
431
+ _cancelReconnect() {
432
+ if (this._wsReconnectTimer) {
433
+ clearTimeout(this._wsReconnectTimer);
434
+ this._wsReconnectTimer = null;
435
+ }
436
+ this._listenForWake(false);
437
+ }
438
+ /**
439
+ * Dial now if the client is waiting out its reconnect backoff (up to 30 s)
440
+ * instead of letting the wait run out. For the moments the host knows the
441
+ * executor may be reachable again: an executor it restarted is up, the
442
+ * device woke. In a browser the client does this itself on `online` and when
443
+ * the page becomes visible. Does nothing while a socket is open or
444
+ * connecting, after `closeAll()` with nothing to reconnect, or once the
445
+ * executor refused the token.
446
+ */
447
+ reconnectNow() {
448
+ if (!this._wsReconnectTimer || this._ws || this._authFailed !== null)
449
+ return;
450
+ this._cancelReconnect();
451
+ // The executor is likely back, so a failure now starts the backoff over.
452
+ this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;
453
+ this._ensureWs();
454
+ }
455
+ /** Listen for `online` and `visibilitychange` exactly while a reconnect
456
+ * timer is pending. Outside a browser (no `window`) it registers nothing. */
457
+ _listenForWake(on) {
458
+ if (on === this._wakeListening)
459
+ return;
460
+ const win = typeof window !== 'undefined' ? window : undefined;
461
+ if (typeof win?.addEventListener !== 'function')
462
+ return;
463
+ const doc = typeof document !== 'undefined' && typeof document.addEventListener === 'function' ? document : undefined;
464
+ this._wakeListening = on;
465
+ if (on) {
466
+ win.addEventListener('online', this._onWake);
467
+ doc?.addEventListener('visibilitychange', this._onWake);
468
+ }
469
+ else {
470
+ win.removeEventListener('online', this._onWake);
471
+ doc?.removeEventListener('visibilitychange', this._onWake);
472
+ }
350
473
  }
351
474
  // ── RPC call method ─────────────────────────────────────────────────────
352
475
  /**
@@ -392,7 +515,7 @@ class ApiClient {
392
515
  }, timeoutMs);
393
516
  const onAbort = () => {
394
517
  if (pending.sent && this._ws?.readyState === 1 /* OPEN */) {
395
- this._ws.send(JSON.stringify({ id: nextId(), type: 'request.cancel', params: { targetId: id } }));
518
+ this._send(this._ws, JSON.stringify({ id: nextId(), type: 'request.cancel', params: { targetId: id } }));
396
519
  }
397
520
  settle(() => reject(new DOMException('Aborted', 'AbortError')));
398
521
  };
@@ -415,7 +538,7 @@ class ApiClient {
415
538
  return;
416
539
  }
417
540
  if (this._ws.readyState === 1 /* OPEN */) {
418
- this._ws.send(message);
541
+ this._send(this._ws, message);
419
542
  pending.sent = true;
420
543
  }
421
544
  });
@@ -536,10 +659,7 @@ class ApiClient {
536
659
  clearTimeout(this._watchRetryTimer);
537
660
  this._watchRetryTimer = null;
538
661
  }
539
- if (this._wsReconnectTimer) {
540
- clearTimeout(this._wsReconnectTimer);
541
- this._wsReconnectTimer = null;
542
- }
662
+ this._cancelReconnect();
543
663
  const ws = this._ws;
544
664
  this._ws = null;
545
665
  this._wsOpen = null;
@@ -1841,6 +1961,8 @@ class SfuManager {
1841
1961
  this.rosterUnsubscribe = null;
1842
1962
  this.dataChannelUnsubscribe = null;
1843
1963
  this.disconnectedTimer = null;
1964
+ /** Running while the room's roster leaves this agent out: see `noticeRoster`. */
1965
+ this.unlistedTimer = null;
1844
1966
  this.neighbourhood = neighbourhood;
1845
1967
  this.neighbourhoodUrl = neighbourhoodUrl || "";
1846
1968
  this.roomId = roomId;
@@ -2127,6 +2249,37 @@ class SfuManager {
2127
2249
  this.renegotiationUnsubscribe = null;
2128
2250
  this.rosterUnsubscribe?.();
2129
2251
  this.rosterUnsubscribe = null;
2252
+ this.clearUnlistedTimer();
2253
+ }
2254
+ clearUnlistedTimer() {
2255
+ if (this.unlistedTimer) {
2256
+ clearTimeout(this.unlistedTimer);
2257
+ this.unlistedTimer = null;
2258
+ }
2259
+ }
2260
+ /**
2261
+ * The room's roster no longer lists this agent while `pc` is the call's:
2262
+ * the server has dropped this session, and ICE may not say so. In E6
2263
+ * (CI job 53158) one of six sessions never started a rebuild after a
2264
+ * 20 s outage the server had dropped it for. Rebuild once the roster has
2265
+ * left this agent out for `UNLISTED_GRACE_MS`; a roster that lists it
2266
+ * again in that time cancels, since one published just before this
2267
+ * join landed can arrive after it.
2268
+ */
2269
+ noticeRoster(pc, dids) {
2270
+ if (dids.includes(this.agentDid)) {
2271
+ this.clearUnlistedTimer();
2272
+ return;
2273
+ }
2274
+ if (this.unlistedTimer)
2275
+ return;
2276
+ this.unlistedTimer = setTimeout(() => {
2277
+ this.unlistedTimer = null;
2278
+ if (this.state.peerConnection !== pc)
2279
+ return;
2280
+ console.info("SFU: the room no longer lists this session, rebuilding the call");
2281
+ void this.reconnect();
2282
+ }, SfuManager.UNLISTED_GRACE_MS);
2130
2283
  }
2131
2284
  /** Undo a join that failed part way: its subscription and its connection. */
2132
2285
  abandon(pc) {
@@ -2161,8 +2314,10 @@ class SfuManager {
2161
2314
  if (!ours(roster) || this.state.peerConnection !== pc)
2162
2315
  return;
2163
2316
  void joined.then(() => {
2164
- if (this.state.peerConnection === pc)
2165
- this.applyRoster(roster.participants, true);
2317
+ if (this.state.peerConnection !== pc)
2318
+ return;
2319
+ this.applyRoster(roster.participants, true);
2320
+ this.noticeRoster(pc, roster.participants);
2166
2321
  });
2167
2322
  });
2168
2323
  for (const unsubscribe of previous)
@@ -2376,6 +2531,8 @@ SfuManager.MAX_RECONNECTS = 3;
2376
2531
  SfuManager.REJOIN_WINDOW_MS = 120000;
2377
2532
  /** How long ICE may stay disconnected before a rebuild: the executor's `ICE_DISCONNECT_GRACE`. */
2378
2533
  SfuManager.DISCONNECT_GRACE_MS = 10000;
2534
+ /** How long the roster may leave this agent out before the call is rebuilt. */
2535
+ SfuManager.UNLISTED_GRACE_MS = 3000;
2379
2536
 
2380
2537
  /**
2381
2538
  * Peer-to-peer WebRTC mesh transport for the AD4M SDK Session interface.
@@ -6651,7 +6808,19 @@ var __classPrivateFieldGet$7 = (undefined && undefined.__classPrivateFieldGet) |
6651
6808
  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");
6652
6809
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6653
6810
  };
6654
- 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;
6811
+ 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;
6812
+ /** Delay before the first retry of a failed re-open; it doubles per failure. */
6813
+ const REOPEN_BASE_DELAY_MS = 1000;
6814
+ /** Longest delay between two re-open attempts. */
6815
+ const REOPEN_MAX_DELAY_MS = 60000;
6816
+ /** The delay before re-open attempt `failures + 1`: between half and all of
6817
+ * `REOPEN_BASE_DELAY_MS * 2^(failures - 1)`, capped at
6818
+ * `REOPEN_MAX_DELAY_MS`. The random half spreads the clients of a restarted
6819
+ * executor apart. */
6820
+ function reopenDelay(failures, random = Math.random) {
6821
+ const ceiling = Math.min(REOPEN_BASE_DELAY_MS * 2 ** Math.max(0, failures - 1), REOPEN_MAX_DELAY_MS);
6822
+ return ceiling / 2 + random() * ceiling / 2;
6823
+ }
6655
6824
  /** Apply one update to the last result. Query rows are a multiset: added rows are appended.
6656
6825
  * Throws when the update names an instance that neither the last result nor
6657
6826
  * the update holds: the last result was wrong, and the caller must resync. */
@@ -6688,10 +6857,14 @@ function applyUpdate(result, update) {
6688
6857
  * One live query on the executor. Holds the last result, applies each update
6689
6858
  * to it, calls `resyncSubscription` when a revision is missing, and opens a
6690
6859
  * new subscription after a reconnect (the executor ends a socket's
6691
- * subscriptions when it closes). `onResult` gets every result after the
6692
- * first; `start()` returns the first.
6860
+ * subscriptions when it closes). A re-open that fails (the executor is
6861
+ * still loading the perspective after a restart) is retried with backoff
6862
+ * until it succeeds or the query is disposed; `onStatus` listeners hear
6863
+ * about it (#1595). `onResult` gets every result after the first; `start()`
6864
+ * returns the first.
6693
6865
  */
6694
6866
  class LiveQuery {
6867
+ /** `open` subscribes on the executor; aborting its signal cancels the call. */
6695
6868
  constructor(client, uuid, open, onResult) {
6696
6869
  _LiveQuery_instances.add(this);
6697
6870
  _LiveQuery_client.set(this, void 0);
@@ -6709,45 +6882,73 @@ class LiveQuery {
6709
6882
  _LiveQuery_buffer.set(this, null);
6710
6883
  _LiveQuery_unlisten.set(this, void 0);
6711
6884
  _LiveQuery_unreconnect.set(this, void 0);
6885
+ // Aborts the subscribe call still in flight, for `dispose({ cancelOpening })`.
6886
+ _LiveQuery_opening.set(this, void 0);
6887
+ _LiveQuery_retryTimer.set(this, void 0);
6888
+ _LiveQuery_reopening.set(this, false);
6889
+ _LiveQuery_statusListeners.set(this, new Set()
6890
+ /** `open` subscribes on the executor; aborting its signal cancels the call. */
6891
+ );
6712
6892
  __classPrivateFieldSet$7(this, _LiveQuery_client, client, "f");
6713
6893
  __classPrivateFieldSet$7(this, _LiveQuery_uuid, uuid, "f");
6714
6894
  __classPrivateFieldSet$7(this, _LiveQuery_open, open, "f");
6715
6895
  __classPrivateFieldSet$7(this, _LiveQuery_onResult, onResult, "f");
6716
6896
  __classPrivateFieldSet$7(this, _LiveQuery_unlisten, client.onQueryUpdate(update => __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_receive).call(this, update)), "f");
6717
- __classPrivateFieldSet$7(this, _LiveQuery_unreconnect, client.onReconnect(() => {
6718
- this.start().catch(e => console.error('Error re-opening live query after reconnect:', e));
6719
- }), "f");
6897
+ __classPrivateFieldSet$7(this, _LiveQuery_unreconnect, client.onReconnect(() => __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_reopen).call(this)), "f");
6720
6898
  }
6721
6899
  get id() { return __classPrivateFieldGet$7(this, _LiveQuery_id, "f"); }
6722
6900
  get result() { return __classPrivateFieldGet$7(this, _LiveQuery_result, "f"); }
6901
+ /** Whether a re-open failed and the query is waiting to retry it. */
6902
+ get reopening() { return __classPrivateFieldGet$7(this, _LiveQuery_reopening, "f"); }
6903
+ /** Call `listener` on each failed re-open and when a re-open succeeds
6904
+ * after one failed. Returns a remover. */
6905
+ onStatus(listener) {
6906
+ __classPrivateFieldGet$7(this, _LiveQuery_statusListeners, "f").add(listener);
6907
+ return () => __classPrivateFieldGet$7(this, _LiveQuery_statusListeners, "f").delete(listener);
6908
+ }
6723
6909
  /** Open the subscription (again) and return its initial result. A start
6724
6910
  * that a newer one overtakes resolves with the newer one's result. */
6725
6911
  start() {
6726
6912
  var _a;
6913
+ __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_clearRetry).call(this);
6727
6914
  __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");
6728
6915
  return __classPrivateFieldGet$7(this, _LiveQuery_latest, "f");
6729
6916
  }
6730
- dispose() {
6917
+ /** End the subscription. With `cancelOpening`, a subscribe call still in
6918
+ * flight is cancelled too, so the executor stops computing a first result
6919
+ * nobody waits for (#1595); the pending `start()` then rejects instead of
6920
+ * resolving with that result. */
6921
+ dispose(options = {}) {
6731
6922
  var _a;
6732
6923
  __classPrivateFieldSet$7(this, _LiveQuery_disposed, true, "f");
6733
6924
  __classPrivateFieldSet$7(this, _LiveQuery_generation, (_a = __classPrivateFieldGet$7(this, _LiveQuery_generation, "f"), _a++, _a), "f");
6925
+ __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_clearRetry).call(this);
6926
+ __classPrivateFieldGet$7(this, _LiveQuery_statusListeners, "f").clear();
6734
6927
  __classPrivateFieldGet$7(this, _LiveQuery_unlisten, "f").call(this);
6735
6928
  __classPrivateFieldGet$7(this, _LiveQuery_unreconnect, "f").call(this);
6929
+ if (options.cancelOpening)
6930
+ __classPrivateFieldGet$7(this, _LiveQuery_opening, "f")?.abort();
6736
6931
  if (__classPrivateFieldGet$7(this, _LiveQuery_id, "f"))
6737
6932
  __classPrivateFieldGet$7(this, _LiveQuery_client, "f").disposeQuerySubscription(__classPrivateFieldGet$7(this, _LiveQuery_uuid, "f"), __classPrivateFieldGet$7(this, _LiveQuery_id, "f")).catch(() => { });
6738
6933
  }
6739
6934
  }
6740
- _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) {
6935
+ _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) {
6741
6936
  __classPrivateFieldSet$7(this, _LiveQuery_buffer, [], "f");
6937
+ const opening = new AbortController();
6938
+ __classPrivateFieldSet$7(this, _LiveQuery_opening, opening, "f");
6742
6939
  let subscribed;
6743
6940
  try {
6744
- subscribed = await __classPrivateFieldGet$7(this, _LiveQuery_open, "f").call(this);
6941
+ subscribed = await __classPrivateFieldGet$7(this, _LiveQuery_open, "f").call(this, opening.signal);
6745
6942
  }
6746
6943
  catch (e) {
6747
6944
  if (generation === __classPrivateFieldGet$7(this, _LiveQuery_generation, "f"))
6748
6945
  __classPrivateFieldSet$7(this, _LiveQuery_buffer, null, "f");
6749
6946
  throw e;
6750
6947
  }
6948
+ finally {
6949
+ if (__classPrivateFieldGet$7(this, _LiveQuery_opening, "f") === opening)
6950
+ __classPrivateFieldSet$7(this, _LiveQuery_opening, undefined, "f");
6951
+ }
6751
6952
  if (__classPrivateFieldGet$7(this, _LiveQuery_disposed, "f") || generation !== __classPrivateFieldGet$7(this, _LiveQuery_generation, "f")) {
6752
6953
  __classPrivateFieldGet$7(this, _LiveQuery_client, "f").disposeQuerySubscription(__classPrivateFieldGet$7(this, _LiveQuery_uuid, "f"), subscribed.subscriptionId).catch(() => { });
6753
6954
  // Disposed while opening (e.g. a newer subscribe() on the same
@@ -6757,6 +6958,46 @@ _LiveQuery_client = new WeakMap(), _LiveQuery_uuid = new WeakMap(), _LiveQuery_o
6757
6958
  __classPrivateFieldSet$7(this, _LiveQuery_id, subscribed.subscriptionId, "f");
6758
6959
  __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_replace).call(this, subscribed.revision, subscribed.result);
6759
6960
  return __classPrivateFieldGet$7(this, _LiveQuery_result, "f");
6961
+ }, _LiveQuery_reopen = function _LiveQuery_reopen(failures = 0) {
6962
+ if (__classPrivateFieldGet$7(this, _LiveQuery_disposed, "f"))
6963
+ return;
6964
+ const reopened = this.start();
6965
+ const generation = __classPrivateFieldGet$7(this, _LiveQuery_generation, "f");
6966
+ reopened.then(() => {
6967
+ if (__classPrivateFieldGet$7(this, _LiveQuery_disposed, "f") || generation !== __classPrivateFieldGet$7(this, _LiveQuery_generation, "f") || !__classPrivateFieldGet$7(this, _LiveQuery_reopening, "f"))
6968
+ return;
6969
+ __classPrivateFieldSet$7(this, _LiveQuery_reopening, false, "f");
6970
+ __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_emit).call(this, { state: 'open' });
6971
+ }, error => {
6972
+ if (__classPrivateFieldGet$7(this, _LiveQuery_disposed, "f") || generation !== __classPrivateFieldGet$7(this, _LiveQuery_generation, "f"))
6973
+ return;
6974
+ const retryInMs = reopenDelay(failures + 1);
6975
+ console.error(`Error re-opening live query (attempt ${failures + 1}), retrying in ${Math.round(retryInMs)}ms:`, error);
6976
+ __classPrivateFieldSet$7(this, _LiveQuery_reopening, true, "f");
6977
+ __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_emit).call(this, { state: 'reopening', error, retryInMs });
6978
+ const timer = setTimeout(() => {
6979
+ __classPrivateFieldSet$7(this, _LiveQuery_retryTimer, undefined, "f");
6980
+ __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_reopen).call(this, failures + 1);
6981
+ }, retryInMs);
6982
+ // Node: a pending retry must not keep the process alive.
6983
+ if (typeof timer?.unref === 'function')
6984
+ timer.unref();
6985
+ __classPrivateFieldSet$7(this, _LiveQuery_retryTimer, timer, "f");
6986
+ });
6987
+ }, _LiveQuery_clearRetry = function _LiveQuery_clearRetry() {
6988
+ if (__classPrivateFieldGet$7(this, _LiveQuery_retryTimer, "f") === undefined)
6989
+ return;
6990
+ clearTimeout(__classPrivateFieldGet$7(this, _LiveQuery_retryTimer, "f"));
6991
+ __classPrivateFieldSet$7(this, _LiveQuery_retryTimer, undefined, "f");
6992
+ }, _LiveQuery_emit = function _LiveQuery_emit(status) {
6993
+ for (const listener of [...__classPrivateFieldGet$7(this, _LiveQuery_statusListeners, "f")]) {
6994
+ try {
6995
+ listener(status);
6996
+ }
6997
+ catch (e) {
6998
+ console.error('Error in live query status listener:', e);
6999
+ }
7000
+ }
6760
7001
  }, _LiveQuery_replace = function _LiveQuery_replace(revision, result) {
6761
7002
  __classPrivateFieldSet$7(this, _LiveQuery_revision, revision, "f");
6762
7003
  __classPrivateFieldSet$7(this, _LiveQuery_result, result, "f");
@@ -6805,7 +7046,7 @@ _LiveQuery_client = new WeakMap(), _LiveQuery_uuid = new WeakMap(), _LiveQuery_o
6805
7046
  // Replace the subscription with a new one.
6806
7047
  if (!__classPrivateFieldGet$7(this, _LiveQuery_disposed, "f") && generation === __classPrivateFieldGet$7(this, _LiveQuery_generation, "f")) {
6807
7048
  __classPrivateFieldGet$7(this, _LiveQuery_client, "f").disposeQuerySubscription(__classPrivateFieldGet$7(this, _LiveQuery_uuid, "f"), id).catch(() => { });
6808
- this.start().catch(e => console.error('Error re-opening live query:', e));
7049
+ __classPrivateFieldGet$7(this, _LiveQuery_instances, "m", _LiveQuery_reopen).call(this);
6809
7050
  }
6810
7051
  });
6811
7052
  };
@@ -7586,8 +7827,8 @@ class QuerySubscriptionProxy {
7586
7827
  _QuerySubscriptionProxy_initResolve.set(this, void 0);
7587
7828
  _QuerySubscriptionProxy_initReject.set(this, void 0);
7588
7829
  const open = className === undefined
7589
- ? () => client.subscribeQuery(uuid, query)
7590
- : () => client.modelSubscribe(uuid, className, query);
7830
+ ? (signal) => client.subscribeQuery(uuid, query, { signal })
7831
+ : (signal) => client.modelSubscribe(uuid, className, query, { signal });
7591
7832
  __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_live, new LiveQuery(client, uuid, open, result => __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliver).call(this, result)), "f");
7592
7833
  __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_initialized, new Promise((resolve, reject) => {
7593
7834
  __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_initResolve, resolve, "f");
@@ -7625,9 +7866,23 @@ class QuerySubscriptionProxy {
7625
7866
  __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_callbacks, "f").add(callback);
7626
7867
  return () => __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_callbacks, "f").delete(callback);
7627
7868
  }
7628
- /** End the subscription on the executor and drop all callbacks. */
7629
- dispose() {
7630
- __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_live, "f").dispose();
7869
+ /** Whether the query lost its subscription (a reconnect, a failed
7870
+ * resync), could not open it again yet and is retrying: `result` is then
7871
+ * not live. */
7872
+ get reopening() {
7873
+ return __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_live, "f").reopening;
7874
+ }
7875
+ /** Call `listener` on each failed re-open of the subscription and when a
7876
+ * re-open succeeds after one failed (see {@link LiveQueryStatus}).
7877
+ * Returns a remover. */
7878
+ onStatus(listener) {
7879
+ return __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_live, "f").onStatus(listener);
7880
+ }
7881
+ /** End the subscription on the executor and drop all callbacks. With
7882
+ * `cancelOpening`, a `subscribe()` still waiting on the executor is
7883
+ * cancelled too, and rejects. */
7884
+ dispose(options = {}) {
7885
+ __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_live, "f").dispose(options);
7631
7886
  __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_callbacks, "f").clear();
7632
7887
  }
7633
7888
  }
@@ -7879,6 +8134,19 @@ class PerspectiveProxy {
7879
8134
  observationId, emitDebugEvents, options) {
7880
8135
  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);
7881
8136
  }
8137
+ /**
8138
+ * Ask a model something about this perspective, or ask it to change something, with the
8139
+ * executor's own tools — including the tools apps install for their records. It reads freely;
8140
+ * it writes only with the tools named in `settings.writeTools`, as you. Answers with the
8141
+ * model's final reply.
8142
+ *
8143
+ * @param messages the conversation so far, the person's request last
8144
+ * @param settings `context` (what the person is looking at), `writeTools`, `model`, `maxToolCalls`
8145
+ * @param options `signal` / `timeoutMs` (default {@link LONG_TIMEOUT_MS})
8146
+ */
8147
+ async runAgent(messages, settings, options) {
8148
+ return await __classPrivateFieldGet$6(this, _PerspectiveProxy_client, "f").runAgent(__classPrivateFieldGet$6(this, _PerspectiveProxy_handle, "f").uuid, messages, settings, options);
8149
+ }
7882
8150
  /**
7883
8151
  * Register a neighbourhood auto-processor on this perspective. The executor
7884
8152
  * then runs interpretation automatically over new source items (like Flux
@@ -8253,6 +8521,12 @@ class PerspectiveProxy {
8253
8521
  /**
8254
8522
  * Adds a pre-signed LinkExpression to the perspective.
8255
8523
  *
8524
+ * The executor checks the signature against `link.author` and stores the
8525
+ * verdict as `proof.valid`. If the same link (author, source, predicate,
8526
+ * target and timestamp) is already stored with a signature that verifies,
8527
+ * its stored proof is kept. The expression passed here is still returned
8528
+ * and, when Shared, committed to the neighbourhood as given.
8529
+ *
8256
8530
  * @param link - The signed LinkExpression to add
8257
8531
  * @param status - Whether the link should be shared
8258
8532
  * @param batchId - Optional batch ID to group this operation with others
@@ -8881,16 +9155,11 @@ class PerspectiveProxy {
8881
9155
  async stringOrTemplateObjectToSubjectClassName(subjectClass) {
8882
9156
  if (typeof subjectClass === "string")
8883
9157
  return subjectClass;
8884
- else {
8885
- let subjectClasses = await this.subjectClassesByTemplate(subjectClass);
8886
- if (subjectClasses[0]) {
8887
- return subjectClasses[0];
8888
- }
8889
- else {
8890
- //@ts-ignore
8891
- return subjectClass.className;
8892
- }
8893
- }
9158
+ // The @Model decorator names the class, as in createSubject: no lookup.
9159
+ // Only an undecorated object is matched by its properties.
9160
+ const obj = subjectClass;
9161
+ return obj.className || obj.constructor?.className || obj.constructor?.prototype?.className
9162
+ || (await this.subjectClassesByTemplate(obj))[0];
8894
9163
  }
8895
9164
  /**
8896
9165
  * Creates a new subject instance of the given subject class
@@ -9556,7 +9825,15 @@ class PerspectiveProxy {
9556
9825
  * refuses a Prolog query (400): Prolog live queries are not supported. */
9557
9826
  async subscribeQuery(query) {
9558
9827
  const subscription = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet$6(this, _PerspectiveProxy_client, "f"));
9559
- await subscription.subscribe();
9828
+ try {
9829
+ await subscription.subscribe();
9830
+ }
9831
+ catch (e) {
9832
+ // Nobody gets the proxy, so nobody can dispose it: left as is, it
9833
+ // would re-open on every reconnect and retry for good (#1595).
9834
+ subscription.dispose({ cancelOpening: true });
9835
+ throw e;
9836
+ }
9560
9837
  return subscription;
9561
9838
  }
9562
9839
  }
@@ -9648,8 +9925,9 @@ class PerspectiveClient {
9648
9925
  return JSON.parse(result);
9649
9926
  }
9650
9927
  /** Open a live SPARQL query. Updates arrive through {@link onQueryUpdate}. */
9651
- async subscribeQuery(uuid, query) {
9652
- return __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call('perspective.subscribeQuery', { uuid, query });
9928
+ /** `options.signal` cancels the call, and the executor stops computing the first result. */
9929
+ async subscribeQuery(uuid, query, options) {
9930
+ return __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call('perspective.subscribeQuery', { uuid, query }, options);
9653
9931
  }
9654
9932
  /** Every `query-subscription-update` event on this client's socket. */
9655
9933
  onQueryUpdate(cb) {
@@ -9682,8 +9960,9 @@ class PerspectiveClient {
9682
9960
  return JSON.parse(resultJson);
9683
9961
  }
9684
9962
  /** Open a live model query over one class or several. Updates arrive through {@link onQueryUpdate}. */
9685
- async modelSubscribe(uuid, className, queryJson) {
9686
- return __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, ...classParams(className), query_json: queryJson });
9963
+ /** `options.signal` cancels the call, and the executor stops computing the first result. */
9964
+ async modelSubscribe(uuid, className, queryJson, options) {
9965
+ return __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, ...classParams(className), query_json: queryJson }, options);
9687
9966
  }
9688
9967
  async add(name) {
9689
9968
  const handle = await __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call('perspective.create', { name });
@@ -9769,6 +10048,19 @@ class PerspectiveClient {
9769
10048
  emitDebugEvents,
9770
10049
  }, options);
9771
10050
  }
10051
+ /**
10052
+ * A conversation with a model in this perspective, using the executor's own tools: the tools
10053
+ * that read this perspective, and only the writing tools named in `writeTools`. Every tool a
10054
+ * session offers acts on this perspective alone, so tools about other perspectives, the agent
10055
+ * or the node (listing or publishing perspectives, the profile) are not available. Runs as the
10056
+ * caller, with the caller's capabilities, and answers with the model's final reply.
10057
+ *
10058
+ * Defaults to {@link LONG_TIMEOUT_MS}: an agent may read documentation and make many tool
10059
+ * calls before it answers.
10060
+ */
10061
+ async runAgent(uuid, messages, settings, options) {
10062
+ return __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call('perspective.runAgent', { uuid, messages, ...settings }, options);
10063
+ }
9772
10064
  /**
9773
10065
  * Register a neighbourhood auto-processor on this perspective. The executor's
9774
10066
  * watch loop then runs interpretation automatically over new source items
@@ -18559,6 +18851,9 @@ function buildSPARQLWhereFilters(metadata, _allRelationsMetadata, where) {
18559
18851
  * Allows building queries with a chainable interface and either
18560
18852
  * running them once or subscribing to real-time updates.
18561
18853
  */
18854
+ /** What a subscription compares to skip a callback whose results equal the
18855
+ * last ones emitted (a resync or a reconnect re-open of an unchanged result). */
18856
+ const fingerprint = (value) => JSON.stringify(value, (_, v) => (typeof v === 'function' ? undefined : v));
18562
18857
  /** Query builder for Ad4mModel queries.
18563
18858
  * Allows building queries with a fluent interface and either running them once
18564
18859
  * or subscribing to updates.
@@ -18613,6 +18908,10 @@ class ModelQueryBuilder {
18613
18908
  }
18614
18909
  return this.ctor.parseModelResult(this.perspective, raw, include, properties);
18615
18910
  }
18911
+ /** Snapshot instances for dirty tracking, as `execute` does for its rows. */
18912
+ takeSnapshots(instances) {
18913
+ this.ctor.takeSnapshots(instances, this.queryParams.include);
18914
+ }
18616
18915
  /** Ends the current subscription, if any, on the client and the executor. */
18617
18916
  dispose() {
18618
18917
  if (this.currentSubscription) {
@@ -18982,7 +19281,6 @@ class ModelQueryBuilder {
18982
19281
  this.dispose();
18983
19282
  const parseResults = (raw) => this.parse(raw);
18984
19283
  // Suppress callbacks whose parsed results equal the last ones emitted.
18985
- const fingerprint = (results) => JSON.stringify(results, (_, v) => (typeof v === 'function' ? undefined : v));
18986
19284
  let lastFingerprint = null;
18987
19285
  const { initial } = await this.live(this.queryParams, (raw) => {
18988
19286
  try {
@@ -19133,73 +19431,46 @@ class ModelQueryBuilder {
19133
19431
  *
19134
19432
  */
19135
19433
  async paginateSubscribe(pageSize, pageNumber, callback) {
19136
- // Clean up any existing subscription
19137
19434
  this.dispose();
19138
- // Subscribe to the full result set (no limit/offset) so the subscription
19139
- // detects changes anywhere in the dataset; each change re-reads the page.
19140
- const subscriptionParams = { ...(this.queryParams || {}) };
19141
- delete subscriptionParams.limit;
19142
- delete subscriptionParams.offset;
19143
- // Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)
19435
+ // Subscribe to the page itself. Since #1237 the executor re-runs a paged
19436
+ // subscription when a record outside the page starts or stops matching
19437
+ // (the `joins` and `scan` trigger rules), and a model result carries
19438
+ // `totalCount`, so a write outside the page still changes the result and
19439
+ // is pushed. Each page is built from the pushed rows: no second query, and
19440
+ // the executor hydrates one page per change rather than every match.
19441
+ // Pushes arrive in revision order, so the last callback is the latest
19442
+ // state (#1051). After dispose() the live query delivers nothing.
19144
19443
  const paginatedQuery = {
19145
19444
  ...(this.queryParams || {}),
19146
19445
  limit: pageSize,
19147
19446
  offset: pageSize * (pageNumber - 1),
19148
19447
  count: true,
19149
19448
  };
19150
- // One read in flight. A dispatch while a read is running sets `pending`
19151
- // so a fetch always completes after the last dispatch. The generation
19152
- // counter from #1020 dropped superseded fetches, but ordered them by
19153
- // start time rather than by how fresh the data they read was — two
19154
- // back-to-back dispatches could keep the fetch that saw 1 model and
19155
- // drop the one that saw 2, after which the server has nothing further
19156
- // to say (issue #1051 / CI: "Paginate callback did not see second model save").
19157
- // After dispose() no read starts and no result is delivered, including
19158
- // a read that was already in flight when dispose() ran.
19159
- let disposed = false;
19160
- let fetching = false;
19161
- let pending = false;
19162
- const processResults = async () => {
19163
- if (disposed)
19164
- return;
19165
- if (fetching) {
19166
- pending = true;
19167
- return;
19168
- }
19169
- fetching = true;
19449
+ // As subscribe(): a callback fires only when the rows or totalCount
19450
+ // differ from the last page emitted, not on a resync or a reconnect
19451
+ // re-open of an unchanged page.
19452
+ let lastFingerprint = null;
19453
+ const toPage = (raw) => {
19454
+ const results = this.parse(raw);
19455
+ const fp = fingerprint([results, raw?.totalCount]);
19456
+ this.takeSnapshots(results);
19457
+ return { page: { results, totalCount: raw?.totalCount, pageSize, pageNumber }, fp };
19458
+ };
19459
+ const { initial } = await this.live(paginatedQuery, (raw) => {
19170
19460
  try {
19171
- const { results, totalCount } = await this.execute(paginatedQuery);
19172
- if (!disposed)
19173
- callback({ results, totalCount, pageSize, pageNumber });
19461
+ const { page, fp } = toPage(raw);
19462
+ if (fp === lastFingerprint)
19463
+ return;
19464
+ lastFingerprint = fp;
19465
+ callback(page);
19174
19466
  }
19175
- finally {
19176
- fetching = false;
19177
- if (pending) {
19178
- pending = false;
19179
- // Detached from the caller's promise: needs its own handler, or a
19180
- // rejection here is unhandled.
19181
- processResults().catch(e => console.error('Paginate subscription error:', e));
19182
- }
19467
+ catch (e) {
19468
+ console.error('Paginate subscription error:', e);
19183
19469
  }
19184
- };
19185
- const { live } = await this.live(subscriptionParams, () => {
19186
- processResults().catch(e => console.error('Paginate subscription error:', e));
19187
19470
  });
19188
- if (this.currentSubscription === live) {
19189
- this.currentSubscription = {
19190
- dispose: () => {
19191
- disposed = true;
19192
- live.dispose();
19193
- },
19194
- };
19195
- }
19196
- else {
19197
- // Disposed, or overtaken by a later subscribe, while opening: deliver nothing.
19198
- disposed = true;
19199
- }
19200
- // Initial fetch (single call with count: true)
19201
- const { results, totalCount } = await this.execute(paginatedQuery);
19202
- return { results, totalCount, pageSize, pageNumber };
19471
+ const { page, fp } = toPage(initial);
19472
+ lastFingerprint = fp;
19473
+ return page;
19203
19474
  }
19204
19475
  /**
19205
19476
  * Subscribes to paginated results updates using SPARQL.
@@ -20361,6 +20632,20 @@ class Ad4mModel {
20361
20632
  return [];
20362
20633
  return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));
20363
20634
  }
20635
+ /**
20636
+ * Snapshot freshly built instances for dirty tracking, with the relations
20637
+ * `include` loaded (its `$`-prefixed projection keys are not relations).
20638
+ * Used by every query path, and by ModelQueryBuilder for pushed results.
20639
+ * @internal
20640
+ */
20641
+ static takeSnapshots(instances, include) {
20642
+ const relations = include
20643
+ ? Object.fromEntries(Object.entries(include).filter(([k]) => !k.startsWith('$')))
20644
+ : undefined;
20645
+ const snapshot = relations && Object.keys(relations).length > 0 ? relations : undefined;
20646
+ for (const inst of instances)
20647
+ inst.takeSnapshot?.(snapshot);
20648
+ }
20364
20649
  // ── One query over several classes (#1238) ────────────────────────────────
20365
20650
  /**
20366
20651
  * Build the wire parameters for one query over several classes.
@@ -20462,12 +20747,7 @@ class Ad4mModel {
20462
20747
  const { classNames, queryJson } = Ad4mModel.prepareUnionQueryParams(classes, query);
20463
20748
  const result = await perspective.modelQuery(classNames, queryJson, options);
20464
20749
  const results = Ad4mModel.parseUnionResult(classes, perspective, result, query.include, query.properties);
20465
- const snapshotRelations = query.include
20466
- ? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith('$')))
20467
- : undefined;
20468
- for (const inst of results) {
20469
- inst.takeSnapshot?.(snapshotRelations && Object.keys(snapshotRelations).length > 0 ? snapshotRelations : undefined);
20470
- }
20750
+ Ad4mModel.takeSnapshots(results, query.include);
20471
20751
  return { results, totalCount: result.totalCount };
20472
20752
  }
20473
20753
  /**
@@ -20533,13 +20813,7 @@ class Ad4mModel {
20533
20813
  const instances = result.instances.map((json) => {
20534
20814
  return jsonToModelInstance(this, perspective, json, query.include, query.properties);
20535
20815
  });
20536
- // Take snapshots for dirty tracking (exclude $-prefixed projection keys)
20537
- const snapshotRelations = query.include
20538
- ? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith('$')))
20539
- : undefined;
20540
- for (const inst of instances) {
20541
- inst.takeSnapshot(snapshotRelations && Object.keys(snapshotRelations).length > 0 ? snapshotRelations : undefined);
20542
- }
20816
+ Ad4mModel.takeSnapshots(instances, query.include);
20543
20817
  return {
20544
20818
  results: instances,
20545
20819
  totalCount: result.totalCount,
@@ -21684,6 +21958,14 @@ class Ad4mClient {
21684
21958
  onAuthFailed(callback) {
21685
21959
  return __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f").onAuthFailed(callback);
21686
21960
  }
21961
+ /**
21962
+ * Reconnect now if the connection to the executor dropped and the client is
21963
+ * waiting out its backoff: for a host that knows the executor is back (it
21964
+ * restarted it, or the device woke). A no-op while connected or connecting.
21965
+ */
21966
+ reconnectNow() {
21967
+ __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f").reconnectNow();
21968
+ }
21687
21969
  /** Close all event connections and clear in-memory caches */
21688
21970
  close() {
21689
21971
  __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f").clearByDidCache();
@@ -21835,13 +22117,13 @@ class LanguageLanguageInput {
21835
22117
  * const runs = await InterpretationRun.findAll(perspective);
21836
22118
  * const configs = await AutoProcessorConfig.findAll(perspective);
21837
22119
  */
21838
- var __decorate$3 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22120
+ var __decorate$4 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
21839
22121
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
21840
22122
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21841
22123
  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;
21842
22124
  return c > 3 && r && Object.defineProperty(target, key, r), r;
21843
22125
  };
21844
- var __metadata$3 = (undefined && undefined.__metadata) || function (k, v) {
22126
+ var __metadata$4 = (undefined && undefined.__metadata) || function (k, v) {
21845
22127
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
21846
22128
  };
21847
22129
  // ── AutoProcessorConfig ─────────────────────────────────────────────────────
@@ -21882,71 +22164,71 @@ let AutoProcessorConfig = class AutoProcessorConfig extends Ad4mModel {
21882
22164
  // `batchMax` + `claimTtlMs` — the Rust SDNA takes the same shape.
21883
22165
  }
21884
22166
  };
21885
- __decorate$3([
22167
+ __decorate$4([
21886
22168
  Property({ through: "ad4m://processor_id", required: true, identity: true }),
21887
- __metadata$3("design:type", String)
22169
+ __metadata$4("design:type", String)
21888
22170
  ], AutoProcessorConfig.prototype, "processorId", void 0);
21889
- __decorate$3([
22171
+ __decorate$4([
21890
22172
  Property({ through: "ad4m://source_scope_query", required: true }),
21891
- __metadata$3("design:type", String)
22173
+ __metadata$4("design:type", String)
21892
22174
  ], AutoProcessorConfig.prototype, "sourceScopeQuery", void 0);
21893
- __decorate$3([
22175
+ __decorate$4([
21894
22176
  Optional({ through: "ad4m://base_prefix" }),
21895
- __metadata$3("design:type", String)
22177
+ __metadata$4("design:type", String)
21896
22178
  ], AutoProcessorConfig.prototype, "basePrefix", void 0);
21897
- __decorate$3([
22179
+ __decorate$4([
21898
22180
  HasMany({ through: "ad4m://interpretation_class", datatype: "xsd:string" }),
21899
- __metadata$3("design:type", Array)
22181
+ __metadata$4("design:type", Array)
21900
22182
  ], AutoProcessorConfig.prototype, "interpretationClasses", void 0);
21901
- __decorate$3([
22183
+ __decorate$4([
21902
22184
  HasMany({ through: "ad4m://flow", datatype: "xsd:string" }),
21903
- __metadata$3("design:type", Array)
22185
+ __metadata$4("design:type", Array)
21904
22186
  ], AutoProcessorConfig.prototype, "flows", void 0);
21905
- __decorate$3([
22187
+ __decorate$4([
21906
22188
  Property({ through: "ad4m://debounce_ms", required: true }),
21907
- __metadata$3("design:type", String)
22189
+ __metadata$4("design:type", String)
21908
22190
  ], AutoProcessorConfig.prototype, "debounceMs", void 0);
21909
- __decorate$3([
22191
+ __decorate$4([
21910
22192
  Optional({ through: "ad4m://batch_min" }),
21911
- __metadata$3("design:type", String)
22193
+ __metadata$4("design:type", String)
21912
22194
  ], AutoProcessorConfig.prototype, "batchMin", void 0);
21913
- __decorate$3([
22195
+ __decorate$4([
21914
22196
  Property({ through: "ad4m://batch_max", required: true }),
21915
- __metadata$3("design:type", String)
22197
+ __metadata$4("design:type", String)
21916
22198
  ], AutoProcessorConfig.prototype, "batchMax", void 0);
21917
- __decorate$3([
22199
+ __decorate$4([
21918
22200
  Optional({ through: "ad4m://max_wait_ms" }),
21919
- __metadata$3("design:type", String)
22201
+ __metadata$4("design:type", String)
21920
22202
  ], AutoProcessorConfig.prototype, "maxWaitMs", void 0);
21921
- __decorate$3([
22203
+ __decorate$4([
21922
22204
  Property({ through: "ad4m://claim_ttl_ms", required: true }),
21923
- __metadata$3("design:type", String)
22205
+ __metadata$4("design:type", String)
21924
22206
  ], AutoProcessorConfig.prototype, "claimTtlMs", void 0);
21925
- __decorate$3([
22207
+ __decorate$4([
21926
22208
  Optional({ through: "ad4m://source_window_ms" }),
21927
- __metadata$3("design:type", String)
22209
+ __metadata$4("design:type", String)
21928
22210
  ], AutoProcessorConfig.prototype, "sourceWindowMs", void 0);
21929
- __decorate$3([
22211
+ __decorate$4([
21930
22212
  Optional({ through: "ad4m://dedup_strategy" }),
21931
- __metadata$3("design:type", String)
22213
+ __metadata$4("design:type", String)
21932
22214
  ], AutoProcessorConfig.prototype, "dedupStrategy", void 0);
21933
- __decorate$3([
22215
+ __decorate$4([
21934
22216
  Optional({ through: "ad4m://existing_scope" }),
21935
- __metadata$3("design:type", String)
22217
+ __metadata$4("design:type", String)
21936
22218
  ], AutoProcessorConfig.prototype, "existingScope", void 0);
21937
- __decorate$3([
22219
+ __decorate$4([
21938
22220
  Optional({ through: "ad4m://mint_scope" }),
21939
- __metadata$3("design:type", String)
22221
+ __metadata$4("design:type", String)
21940
22222
  ], AutoProcessorConfig.prototype, "mintScope", void 0);
21941
- __decorate$3([
22223
+ __decorate$4([
21942
22224
  Optional({ through: "ad4m://max_tool_calls" }),
21943
- __metadata$3("design:type", String)
22225
+ __metadata$4("design:type", String)
21944
22226
  ], AutoProcessorConfig.prototype, "maxToolCalls", void 0);
21945
- __decorate$3([
22227
+ __decorate$4([
21946
22228
  Optional({ through: "ad4m://emit_debug_events", resolveLanguage: "literal" }),
21947
- __metadata$3("design:type", String)
22229
+ __metadata$4("design:type", String)
21948
22230
  ], AutoProcessorConfig.prototype, "emitDebugEvents", void 0);
21949
- AutoProcessorConfig = __decorate$3([
22231
+ AutoProcessorConfig = __decorate$4([
21950
22232
  Model$1({ name: "AutoProcessor" })
21951
22233
  ], AutoProcessorConfig);
21952
22234
  // ── InterpretationRun ───────────────────────────────────────────────────────
@@ -21970,39 +22252,39 @@ let InterpretationRun = class InterpretationRun extends Ad4mModel {
21970
22252
  this.sources = [];
21971
22253
  }
21972
22254
  };
21973
- __decorate$3([
22255
+ __decorate$4([
21974
22256
  Property({ through: "ad4m://interp/run_id", required: true, identity: true }),
21975
- __metadata$3("design:type", String)
22257
+ __metadata$4("design:type", String)
21976
22258
  ], InterpretationRun.prototype, "runId", void 0);
21977
- __decorate$3([
22259
+ __decorate$4([
21978
22260
  Optional({ through: "ad4m://interp/model" }),
21979
- __metadata$3("design:type", String)
22261
+ __metadata$4("design:type", String)
21980
22262
  ], InterpretationRun.prototype, "model", void 0);
21981
- __decorate$3([
22263
+ __decorate$4([
21982
22264
  Optional({ through: "ad4m://interp/prompt_version" }),
21983
- __metadata$3("design:type", String)
22265
+ __metadata$4("design:type", String)
21984
22266
  ], InterpretationRun.prototype, "promptVersion", void 0);
21985
- __decorate$3([
22267
+ __decorate$4([
21986
22268
  Optional({ through: "ad4m://interp/ran_at" }),
21987
- __metadata$3("design:type", String)
22269
+ __metadata$4("design:type", String)
21988
22270
  ], InterpretationRun.prototype, "ranAt", void 0);
21989
- __decorate$3([
22271
+ __decorate$4([
21990
22272
  Optional({ through: "ad4m://interp/processor" }),
21991
- __metadata$3("design:type", String)
22273
+ __metadata$4("design:type", String)
21992
22274
  ], InterpretationRun.prototype, "processor", void 0);
21993
- __decorate$3([
22275
+ __decorate$4([
21994
22276
  HasMany({ through: "ad4m://interp/sources", datatype: "xsd:string" }),
21995
- __metadata$3("design:type", Array)
22277
+ __metadata$4("design:type", Array)
21996
22278
  ], InterpretationRun.prototype, "sources", void 0);
21997
- __decorate$3([
22279
+ __decorate$4([
21998
22280
  Optional({ through: "ad4m://interp/debug_prompt", resolveLanguage: "literal" }),
21999
- __metadata$3("design:type", String)
22281
+ __metadata$4("design:type", String)
22000
22282
  ], InterpretationRun.prototype, "debugPrompt", void 0);
22001
- __decorate$3([
22283
+ __decorate$4([
22002
22284
  Optional({ through: "ad4m://interp/debug_response", resolveLanguage: "literal" }),
22003
- __metadata$3("design:type", String)
22285
+ __metadata$4("design:type", String)
22004
22286
  ], InterpretationRun.prototype, "debugResponse", void 0);
22005
- InterpretationRun = __decorate$3([
22287
+ InterpretationRun = __decorate$4([
22006
22288
  Model$1({ name: "InterpretationRun" })
22007
22289
  ], InterpretationRun);
22008
22290
  // ── InterpretationOverlay ───────────────────────────────────────────────────
@@ -22032,15 +22314,15 @@ let InterpretationOverlay = class InterpretationOverlay extends Ad4mModel {
22032
22314
  this.kind = "";
22033
22315
  }
22034
22316
  };
22035
- __decorate$3([
22317
+ __decorate$4([
22036
22318
  Property({ through: "ad4m://interp/kind", required: true }),
22037
- __metadata$3("design:type", String)
22319
+ __metadata$4("design:type", String)
22038
22320
  ], InterpretationOverlay.prototype, "kind", void 0);
22039
- __decorate$3([
22321
+ __decorate$4([
22040
22322
  Optional({ through: "ad4m://interp/run" }),
22041
- __metadata$3("design:type", String)
22323
+ __metadata$4("design:type", String)
22042
22324
  ], InterpretationOverlay.prototype, "run", void 0);
22043
- InterpretationOverlay = __decorate$3([
22325
+ InterpretationOverlay = __decorate$4([
22044
22326
  Model$1({ name: "InterpretationOverlay" })
22045
22327
  ], InterpretationOverlay);
22046
22328
 
@@ -22064,13 +22346,13 @@ InterpretationOverlay = __decorate$3([
22064
22346
  * - the SDNA-parity test locks TS/Rust drift against
22065
22347
  * `rust-executor/src/perspectives/hardwired_sdna/flow_transition_proposal.json`.
22066
22348
  */
22067
- var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22349
+ var __decorate$3 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22068
22350
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22069
22351
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22070
22352
  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;
22071
22353
  return c > 3 && r && Object.defineProperty(target, key, r), r;
22072
22354
  };
22073
- var __metadata$2 = (undefined && undefined.__metadata) || function (k, v) {
22355
+ var __metadata$3 = (undefined && undefined.__metadata) || function (k, v) {
22074
22356
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22075
22357
  };
22076
22358
  /**
@@ -22177,55 +22459,55 @@ let FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel {
22177
22459
  // of the proposal's own links (all written together during create_subject).
22178
22460
  }
22179
22461
  };
22180
- __decorate$2([
22462
+ __decorate$3([
22181
22463
  Property({ through: "ad4m://flow/instance", required: true, identity: true }),
22182
- __metadata$2("design:type", String)
22464
+ __metadata$3("design:type", String)
22183
22465
  ], FlowTransitionProposal.prototype, "flowInstance", void 0);
22184
- __decorate$2([
22466
+ __decorate$3([
22185
22467
  Property({ through: "ad4m://flow/from_state", required: true }),
22186
- __metadata$2("design:type", String)
22468
+ __metadata$3("design:type", String)
22187
22469
  ], FlowTransitionProposal.prototype, "fromState", void 0);
22188
- __decorate$2([
22470
+ __decorate$3([
22189
22471
  Property({ through: "ad4m://flow/to_state", required: true }),
22190
- __metadata$2("design:type", String)
22472
+ __metadata$3("design:type", String)
22191
22473
  ], FlowTransitionProposal.prototype, "toState", void 0);
22192
- __decorate$2([
22474
+ __decorate$3([
22193
22475
  Property({ through: "ad4m://flow/proposer", required: true, getter: PROPOSER_GETTER, datatype: "xsd:string" }),
22194
- __metadata$2("design:type", String)
22476
+ __metadata$3("design:type", String)
22195
22477
  ], FlowTransitionProposal.prototype, "proposer", void 0);
22196
- __decorate$2([
22478
+ __decorate$3([
22197
22479
  HasMany({ through: "ad4m://flow/evidence", datatype: "xsd:string" }),
22198
- __metadata$2("design:type", Array)
22480
+ __metadata$3("design:type", Array)
22199
22481
  ], FlowTransitionProposal.prototype, "evidence", void 0);
22200
- __decorate$2([
22482
+ __decorate$3([
22201
22483
  Property({ through: "ad4m://flow/evidence_hashes", required: true }),
22202
- __metadata$2("design:type", String)
22484
+ __metadata$3("design:type", String)
22203
22485
  ], FlowTransitionProposal.prototype, "evidenceHashes", void 0);
22204
- __decorate$2([
22486
+ __decorate$3([
22205
22487
  HasMany({ through: "ad4m://flow/output", datatype: "xsd:string" }),
22206
- __metadata$2("design:type", Array)
22488
+ __metadata$3("design:type", Array)
22207
22489
  ], FlowTransitionProposal.prototype, "outputs", void 0);
22208
- __decorate$2([
22490
+ __decorate$3([
22209
22491
  Property({ through: "ad4m://flow/outputs_hash" }),
22210
- __metadata$2("design:type", String)
22492
+ __metadata$3("design:type", String)
22211
22493
  ], FlowTransitionProposal.prototype, "outputsHash", void 0);
22212
- __decorate$2([
22494
+ __decorate$3([
22213
22495
  Property({ through: "ad4m://flow/nonce" }),
22214
- __metadata$2("design:type", String)
22496
+ __metadata$3("design:type", String)
22215
22497
  ], FlowTransitionProposal.prototype, "nonce", void 0);
22216
- __decorate$2([
22498
+ __decorate$3([
22217
22499
  Optional({ through: "ad4m://flow/run_uri" }),
22218
- __metadata$2("design:type", String)
22500
+ __metadata$3("design:type", String)
22219
22501
  ], FlowTransitionProposal.prototype, "runUri", void 0);
22220
- __decorate$2([
22502
+ __decorate$3([
22221
22503
  Optional({ through: "ad4m://flow/rationale" }),
22222
- __metadata$2("design:type", String)
22504
+ __metadata$3("design:type", String)
22223
22505
  ], FlowTransitionProposal.prototype, "rationale", void 0);
22224
- __decorate$2([
22506
+ __decorate$3([
22225
22507
  HasMany({ through: "ad4m://acceptedBy", getter: ACCEPTED_BY_GETTER, readOnly: true }),
22226
- __metadata$2("design:type", Array)
22508
+ __metadata$3("design:type", Array)
22227
22509
  ], FlowTransitionProposal.prototype, "acceptedBy", void 0);
22228
- FlowTransitionProposal = __decorate$2([
22510
+ FlowTransitionProposal = __decorate$3([
22229
22511
  Model$1({ name: "FlowTransitionProposal" })
22230
22512
  ], FlowTransitionProposal);
22231
22513
  // ── FlowInstanceRecord ──────────────────────────────────────────────────────
@@ -22285,25 +22567,25 @@ let FlowInstanceRecord = class FlowInstanceRecord extends Ad4mModel {
22285
22567
  // of the instance's own links (all written together during `mint_flow_instance`).
22286
22568
  }
22287
22569
  };
22288
- __decorate$2([
22570
+ __decorate$3([
22289
22571
  Property({ through: "ad4m://flow/flow_uri", required: true, identity: true }),
22290
- __metadata$2("design:type", String)
22572
+ __metadata$3("design:type", String)
22291
22573
  ], FlowInstanceRecord.prototype, "flowUri", void 0);
22292
- __decorate$2([
22574
+ __decorate$3([
22293
22575
  Property({ through: "ad4m://flow/base", required: true }),
22294
- __metadata$2("design:type", String)
22576
+ __metadata$3("design:type", String)
22295
22577
  ], FlowInstanceRecord.prototype, "subject", void 0);
22296
- FlowInstanceRecord = __decorate$2([
22578
+ FlowInstanceRecord = __decorate$3([
22297
22579
  Model$1({ name: "FlowInstance" })
22298
22580
  ], FlowInstanceRecord);
22299
22581
 
22300
- var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22582
+ var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22301
22583
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22302
22584
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22303
22585
  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;
22304
22586
  return c > 3 && r && Object.defineProperty(target, key, r), r;
22305
22587
  };
22306
- var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22588
+ var __metadata$2 = (undefined && undefined.__metadata) || function (k, v) {
22307
22589
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22308
22590
  };
22309
22591
  /**
@@ -22329,6 +22611,10 @@ var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22329
22611
  * reads it by its URI, `ad4m://TextContent`, so a perspective never stores it
22330
22612
  * and an app class named `TextContent` does not replace it. `register()` on
22331
22613
  * it writes nothing.
22614
+ *
22615
+ * The waker's mention subscription (`get_mention_waker_config`) reads it for
22616
+ * the agent's names in the text. Mention links it reads through
22617
+ * {@link Mentioning}, with text or without.
22332
22618
  */
22333
22619
  let TextContent = class TextContent extends Ad4mModel {
22334
22620
  constructor() {
@@ -22339,14 +22625,70 @@ let TextContent = class TextContent extends Ad4mModel {
22339
22625
  };
22340
22626
  /** The URI the executor reads it by. */
22341
22627
  TextContent.builtinUri = "ad4m://TextContent";
22342
- __decorate$1([
22628
+ __decorate$2([
22343
22629
  Property({ through: "ad4m://text" }),
22344
- __metadata$1("design:type", String)
22630
+ __metadata$2("design:type", String)
22345
22631
  ], TextContent.prototype, "text", void 0);
22346
- TextContent = __decorate$1([
22632
+ TextContent = __decorate$2([
22347
22633
  Model$1({ name: "TextContent", abstract: true })
22348
22634
  ], TextContent);
22349
22635
 
22636
+ var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22637
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22638
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22639
+ 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;
22640
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
22641
+ };
22642
+ var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22643
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22644
+ };
22645
+ /**
22646
+ * The built-in abstract class `Mentioning { mentions }`: a record that
22647
+ * mentions agents — a post, a message, a block of a document. `mentions` is
22648
+ * a relation to their DIDs.
22649
+ *
22650
+ * Querying it reads every class that has a relation named `mentions`, or one
22651
+ * aliased to `mentions`, under any predicate, whether or not the class has
22652
+ * text. A class whose relation has another name aliases it:
22653
+ *
22654
+ * ```typescript
22655
+ * @Model({ name: "Note", implements: [Mentioning] })
22656
+ * class Note extends Ad4mModel {
22657
+ * @HasMany({ through: "app://cc", alias: { Mentioning: "mentions" } })
22658
+ * cc: string[] = [];
22659
+ * }
22660
+ *
22661
+ * const mentioningMe = await Mentioning.findAll(perspective, { where: { mentions: myDid } });
22662
+ * ```
22663
+ *
22664
+ * The waker's mention subscription (`get_mention_waker_config`) reads it: a
22665
+ * record whose `mentions` links the agent's DID, in a link another agent
22666
+ * wrote, wakes the agent whatever its text says. Names in text it reads
22667
+ * through {@link TextContent}.
22668
+ *
22669
+ * Built in: the executor declares it (mirrors
22670
+ * `rust-executor/src/perspectives/hardwired_sdna/mentioning.json`) and reads
22671
+ * it by its URI, `ad4m://Mentioning`, so a perspective never stores it and an
22672
+ * app class named `Mentioning` does not replace it. `register()` on it writes
22673
+ * nothing.
22674
+ */
22675
+ let Mentioning = class Mentioning extends Ad4mModel {
22676
+ constructor() {
22677
+ super(...arguments);
22678
+ /** The agents (DIDs) the record mentions. */
22679
+ this.mentions = [];
22680
+ }
22681
+ };
22682
+ /** The URI the executor reads it by. */
22683
+ Mentioning.builtinUri = "ad4m://Mentioning";
22684
+ __decorate$1([
22685
+ HasMany({ through: "ad4m://mentions" }),
22686
+ __metadata$1("design:type", Array)
22687
+ ], Mentioning.prototype, "mentions", void 0);
22688
+ Mentioning = __decorate$1([
22689
+ Model$1({ name: "Mentioning", abstract: true })
22690
+ ], Mentioning);
22691
+
22350
22692
  var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22351
22693
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22352
22694
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -22995,6 +23337,9 @@ function parseLitBoolean(val) {
22995
23337
  * module (`plugins/ad4m/wakerSubscriptionManager.ts`) rather than carrying its
22996
23338
  * own copy. Any behaviour change belongs here.
22997
23339
  */
23340
+ /** The built-in `Container` (`Container.builtinUri`; not imported, so the
23341
+ * plugin bundle does not pull in the model layer). */
23342
+ const CONTAINER = "ad4m://Container";
22998
23343
  /** A letter, combining mark, digit or underscore: what a term must not touch. */
22999
23344
  const WORD_CHAR = "[\\p{L}\\p{M}\\p{N}_]";
23000
23345
  /**
@@ -23024,14 +23369,6 @@ const BREAKING_TAG = /^<\/?(?:p|div|br|hr|li|ul|ol|h[1-6]|blockquote|pre|tr|td|t
23024
23369
  */
23025
23370
  const ATTRIBUTES = new RegExp(ATTRIBUTE, "g");
23026
23371
  const MENTION_TARGET = /^\s+(?:href|data-id|data-did)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))$/i;
23027
- /**
23028
- * How much of a record's text the word check reads. Dropping markup costs time
23029
- * quadratic in a run of unclosed `<script>`, `<style>` or `<!--` openers, so a
23030
- * very long text could hold the event loop for seconds, and a row that holds
23031
- * no term is checked again on every result while it is in the window. A term
23032
- * past this many characters does not wake.
23033
- */
23034
- const MENTION_TEXT_LIMIT = 16384;
23035
23372
  const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
23036
23373
  function decodeEntities(s) {
23037
23374
  return s.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi, (whole, ref) => {
@@ -23065,6 +23402,14 @@ function readableParts(text) {
23065
23402
  });
23066
23403
  return { visible: decodeEntities(visible), targets };
23067
23404
  }
23405
+ /**
23406
+ * How much of a record's text the word check reads. Dropping markup costs time
23407
+ * quadratic in a run of unclosed `<script>`, `<style>` or `<!--` openers, so a
23408
+ * very long text could hold the event loop for seconds, and a row that holds
23409
+ * no term is checked again on every result while it is in the window. A term
23410
+ * past this many characters does not wake.
23411
+ */
23412
+ const MENTION_TEXT_LIMIT = 16384;
23068
23413
  /**
23069
23414
  * Whether `text` holds one of `terms` as a whole word, case-insensitively:
23070
23415
  * "Data" is in "hi Data!", "@data" and "Data's turn", not in "metadata" or
@@ -23079,7 +23424,9 @@ function readableParts(text) {
23079
23424
  * is how a mention by DID is found when the DID is not in the visible text.
23080
23425
  *
23081
23426
  * The mention query's `contains` matches substrings (model query has no word
23082
- * match); this is the check that keeps "data" from waking on "metadata".
23427
+ * match); this is the check that keeps "data" from waking on "metadata" when
23428
+ * a record is found through its text alone ({@link mentionOf}).
23429
+ *
23083
23430
  * It reads the first {@link MENTION_TEXT_LIMIT} characters only.
23084
23431
  */
23085
23432
  function holdsAWholeWordTerm(text, terms) {
@@ -23093,9 +23440,95 @@ function holdsAWholeWordTerm(text, terms) {
23093
23440
  return new RegExp(`(?<!${WORD_CHAR})${escaped}(?!${WORD_CHAR})`, "iu").test(visible);
23094
23441
  });
23095
23442
  }
23096
- /** The built-in `Container` (`Container.builtinUri`; not imported, so the
23097
- * plugin bundle does not pull in the model layer). */
23098
- const CONTAINER = "ad4m://Container";
23443
+ /** The provenance {@link MentionMessage} carries, from one link. */
23444
+ function provenanceOf(link, via) {
23445
+ const provenance = {
23446
+ verified: link?.proof?.valid === true,
23447
+ via,
23448
+ };
23449
+ if (typeof link?.author === "string")
23450
+ provenance.author = link.author;
23451
+ if (typeof link?.timestamp === "string")
23452
+ provenance.timestamp = link.timestamp;
23453
+ return provenance;
23454
+ }
23455
+ /** The links a model row carries for `key` under `__links`, oldest first. */
23456
+ function rowLinks(row, key) {
23457
+ const links = row?.__links?.[key];
23458
+ return Array.isArray(links) ? links : [];
23459
+ }
23460
+ /** `uri` URI-decoded, or as it is when it is not valid percent-encoding. */
23461
+ function decoded(uri) {
23462
+ try {
23463
+ return decodeURIComponent(uri);
23464
+ }
23465
+ catch {
23466
+ return uri;
23467
+ }
23468
+ }
23469
+ /**
23470
+ * The text a link's target holds, read as the executor reads a string property
23471
+ * (`parse_literal_value`): `literal:string:` decoded, `literal:json:` parsed (a signed
23472
+ * expression to its `data`), any other URI as it is. `undefined` when that is not a string.
23473
+ */
23474
+ function textOf(target) {
23475
+ if (typeof target !== "string")
23476
+ return undefined;
23477
+ if (!target.startsWith("literal:"))
23478
+ return target;
23479
+ const body = target.slice("literal:".length);
23480
+ if (body.startsWith("string:"))
23481
+ return decoded(body.slice("string:".length));
23482
+ if (body.startsWith("json:")) {
23483
+ const json = decoded(body.slice("json:".length));
23484
+ let value;
23485
+ try {
23486
+ value = JSON.parse(json);
23487
+ }
23488
+ catch {
23489
+ return json;
23490
+ }
23491
+ if (value && typeof value === "object" && "data" in value && "author" in value && "proof" in value) {
23492
+ value = value.data;
23493
+ }
23494
+ return typeof value === "string" ? value : undefined;
23495
+ }
23496
+ if (/^(?:number|boolean):/.test(body))
23497
+ return undefined;
23498
+ return target;
23499
+ }
23500
+ /**
23501
+ * Whether a row of one of the mention subscription's two model queries mentions the
23502
+ * subscription's agent, and the provenance of the link it does so in; `null` when it does not.
23503
+ *
23504
+ * - A row of the query over Mentioning: a verified link to the agent's DID that another agent
23505
+ * wrote, in the row's `__links.mentions`. It wakes whatever the record's text says, or
23506
+ * whether it has any: WE's chip label may run into the next word ("@Datai have…"), and a WE
23507
+ * post's mention sits on its root, which has no text. Its provenance is that link's (the
23508
+ * newest such).
23509
+ * - A row of the query over TextContent: the query matched a substring, so the text must hold
23510
+ * a term as a whole word ({@link holdsAWholeWordTerm}), and so must the text of a verified
23511
+ * link another agent wrote, in `__links.text`. Its provenance is that link's (the newest
23512
+ * such). The row's `text` is the newest text link's, whoever wrote it, so it does not say
23513
+ * whose words they are.
23514
+ *
23515
+ * `via` says which it was. A record both queries find wakes once, through the query that
23516
+ * reports it first ({@link WakerSubscriptionManager}).
23517
+ */
23518
+ function mentionOf(row, sub) {
23519
+ const did = sub.did;
23520
+ const byOthers = (links) => links.filter((l) => typeof l.author === "string" && l.author !== did);
23521
+ const linked = byOthers(rowLinks(row, "mentions")).filter((l) => l.data?.target === did && l.proof?.valid === true);
23522
+ if (did && linked.length)
23523
+ return provenanceOf(linked[linked.length - 1], "mentions");
23524
+ const terms = sub.terms ?? [];
23525
+ const names = (text) => typeof text === "string" && holdsAWholeWordTerm(text, terms);
23526
+ const text = Array.isArray(row?.text) ? row.text.join(" ") : row?.text;
23527
+ if (!names(text))
23528
+ return null;
23529
+ const naming = byOthers(rowLinks(row, "text")).filter((l) => l.proof?.valid === true && names(textOf(l.data?.target)));
23530
+ return naming.length ? provenanceOf(naming[naming.length - 1], "text") : null;
23531
+ }
23099
23532
  /**
23100
23533
  * Add a short cause hint to known subscription failures.
23101
23534
  * The executor needs its main key to register a live query; on a restarted
@@ -23141,11 +23574,23 @@ async function withTimeout(promise, ms, message) {
23141
23574
  }
23142
23575
  class WakerSubscriptionManager {
23143
23576
  constructor(options) {
23577
+ /** Per subscription its proxies: one, or a mention subscription's text and mention queries. */
23144
23578
  this.proxies = new Map();
23145
23579
  this.activeSubscriptions = new Map();
23146
23580
  /** Subscriptions the executor rejected, waiting to be re-attempted. */
23147
23581
  this.pendingSubscriptions = new Map();
23148
23582
  this.retryTimer = null;
23583
+ /** Re-attempt rounds in a row that left something pending, for the backoff. */
23584
+ this.retryRounds = 0;
23585
+ /**
23586
+ * Subscriptions that were active until one of their live queries lost its
23587
+ * executor subscription (a reconnect, a failed resync) and failed to open it
23588
+ * again, with the proxies still re-opening. The query retries on its own,
23589
+ * with backoff, so the manager does not subscribe them again; it reports
23590
+ * them as pending instead of active until every proxy is open again, and
23591
+ * keeps persisting them so a restart restores them (#1595).
23592
+ */
23593
+ this.reopening = new Map();
23149
23594
  /**
23150
23595
  * Cancellation tokens for in-flight `subscribe()` calls.
23151
23596
  *
@@ -23185,6 +23630,7 @@ class WakerSubscriptionManager {
23185
23630
  this.QuerySubscriptionProxyCtor = options.QuerySubscriptionProxy ?? null;
23186
23631
  this.previousSeenMessages = options.previousSeenMessages ?? {};
23187
23632
  this.retryPendingMs = options.retryPendingMs ?? 30000;
23633
+ this.maxRetryPendingMs = Math.max(this.retryPendingMs, options.maxRetryPendingMs ?? 300000);
23188
23634
  this.subscribeTimeoutMs = options.subscribeTimeoutMs ?? 15000;
23189
23635
  this.retryWakeMs = options.retryWakeMs ?? 5000;
23190
23636
  }
@@ -23203,28 +23649,51 @@ class WakerSubscriptionManager {
23203
23649
  * If a subscription with the same id already exists, it is disposed first.
23204
23650
  */
23205
23651
  async subscribe(sub) {
23206
- // Dispose existing subscription with same id if any
23207
- this.dispose(sub.id, false);
23652
+ // Dispose existing subscription with same id if any. Not `dispose()`: a
23653
+ // re-attempt must not start the backoff over.
23654
+ this.release(sub.id, false);
23208
23655
  const token = this.beginAttempt(sub.id);
23209
23656
  if (!this.QuerySubscriptionProxyCtor) {
23210
23657
  throw new Error("WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options");
23211
23658
  }
23212
23659
  const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;
23213
- if (sub.type === "mention" && sub.className && !sub.terms?.length) {
23214
- // Without terms the whole-word check cannot run, and every substring
23215
- // ("metadata" for "data") would wake the agent.
23216
- throw new Error(`Waker subscription ${sub.id}: a mention subscription needs its terms (get_mention_waker_config returns them)`);
23660
+ if (sub.type === "mention" &&
23661
+ (!sub.className || !sub.terms?.length || !sub.did || !sub.mentionQuery || !sub.mentionClass)) {
23662
+ // Without terms the whole-word check cannot run, so every substring
23663
+ // ("metadata" for "data") would wake the agent; without the DID no link
23664
+ // can be told to be someone else's; without the mention query a mention
23665
+ // link on a record with no text (a WE post's root) never wakes it.
23666
+ 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)`);
23217
23667
  }
23218
23668
  this.logger.info(`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`);
23219
23669
  this.logger.info(`[waker] ${sub.id}: ${sub.className ? `model query over ${sub.className}` : "SPARQL query"}:\n${sub.query}`);
23670
+ if (sub.mentionQuery) {
23671
+ this.logger.info(`[waker] ${sub.id}: model query over ${sub.mentionClass}:\n${sub.mentionQuery}`);
23672
+ }
23220
23673
  const proxy = sub.className
23221
23674
  ? new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient, sub.className)
23222
23675
  : new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
23676
+ const mentionProxy = sub.mentionQuery
23677
+ ? new QuerySubscriptionProxy(sub.perspective, sub.mentionQuery, this.perspectiveClient, sub.mentionClass)
23678
+ : undefined;
23679
+ const proxies = mentionProxy ? [proxy, mentionProxy] : [proxy];
23680
+ // `cancelOpening`: a handshake given up on must not keep the executor
23681
+ // computing a first result nobody reads; abandoned ones piled up into
23682
+ // hundreds of busy executor threads on staging (#1595).
23683
+ const disposeProxies = () => {
23684
+ for (const p of proxies) {
23685
+ try {
23686
+ p.dispose({ cancelOpening: true });
23687
+ }
23688
+ catch { }
23689
+ }
23690
+ };
23223
23691
  // Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
23224
23692
  // rejects this promise internally when subscribe() fails, and if nobody catches
23225
23693
  // it before the next microtask it crashes the process.
23226
- if (proxy.initialized && typeof proxy.initialized.catch === "function") {
23227
- proxy.initialized.catch(() => { });
23694
+ for (const p of proxies) {
23695
+ if (p.initialized && typeof p.initialized.catch === "function")
23696
+ p.initialized.catch(() => { });
23228
23697
  }
23229
23698
  // One deadline for the whole handshake: `proxy.subscribe()` and the
23230
23699
  // `initialized` promise it resolves share the budget, so a hang in either
@@ -23235,23 +23704,17 @@ class WakerSubscriptionManager {
23235
23704
  ? withTimeout(step, Math.max(0, budgetMs - (Date.now() - startedAt)), `${what} timed out after ${budgetMs}ms`)
23236
23705
  : step;
23237
23706
  try {
23238
- await bounded(proxy.subscribe(), "subscribe handshake");
23707
+ await bounded(Promise.all(proxies.map((p) => p.subscribe())), "subscribe handshake");
23239
23708
  if (this.isStale(sub.id, token)) {
23240
- try {
23241
- proxy.dispose();
23242
- }
23243
- catch { }
23709
+ disposeProxies();
23244
23710
  return;
23245
23711
  }
23246
- await bounded(proxy.initialized, "subscription initialization");
23712
+ await bounded(Promise.all(proxies.map((p) => p.initialized)), "subscription initialization");
23247
23713
  }
23248
23714
  catch (err) {
23249
23715
  const msg = err?.message ?? String(err);
23250
23716
  this.logger.warn(`[waker] ${sub.id}: subscription failed — ${msg}`);
23251
- try {
23252
- proxy.dispose();
23253
- }
23254
- catch { }
23717
+ disposeProxies();
23255
23718
  // A dispose that landed mid-attempt wins: don't re-queue something the
23256
23719
  // caller has since asked us to forget.
23257
23720
  if (this.isStale(sub.id, token))
@@ -23272,17 +23735,16 @@ class WakerSubscriptionManager {
23272
23735
  // turn this into an error result instead of a false "Subscribed" reply.
23273
23736
  throw new Error(`Waker subscription ${sub.id} failed: ${msg}${hintFor(msg)}` +
23274
23737
  (this.retryPendingMs > 0
23275
- ? `. Not listening yet — re-attempting every ${Math.round(this.retryPendingMs / 1000)}s; check ad4m_list_waker_subscriptions.`
23738
+ ? `. 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.`
23276
23739
  : ""));
23277
23740
  }
23278
23741
  if (this.isStale(sub.id, token)) {
23279
- try {
23280
- proxy.dispose();
23281
- }
23282
- catch { }
23742
+ disposeProxies();
23283
23743
  return;
23284
23744
  }
23285
23745
  this.pendingSubscriptions.delete(sub.id);
23746
+ if (this.pendingSubscriptions.size === 0)
23747
+ this.retryRounds = 0;
23286
23748
  this.logger.info(`[waker] ${sub.id}: subscription initialized successfully`);
23287
23749
  // Seed from persisted seen messages so we don't re-wake after restart
23288
23750
  const restored = Object.prototype.hasOwnProperty.call(this.previousSeenMessages, sub.id);
@@ -23294,8 +23756,9 @@ class WakerSubscriptionManager {
23294
23756
  }
23295
23757
  // `opening` is the result the subscription holds when it opens (`proxy.result`): `onResult`
23296
23758
  // only reports later changes, so this is the one chance to see what was written meanwhile.
23297
- const handleResult = async (result, opening = false) => {
23298
- 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)}`);
23759
+ // `of`: the query the result is from, for the log (a mention subscription has two).
23760
+ const handleResult = async (result, opening = false, of = "") => {
23761
+ 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)}`);
23299
23762
  // A model subscription delivers `{ instances }`, SPARQL an array of
23300
23763
  // rows. Anything else (e.g. `false` on a disconnect/reconnect) is
23301
23764
  // ignored.
@@ -23305,26 +23768,25 @@ class WakerSubscriptionManager {
23305
23768
  return;
23306
23769
  }
23307
23770
  if (sub.type === "mention") {
23308
- // For mention subscriptions: track seen record ids.
23309
- // Only wake for records we haven't seen before.
23771
+ // For mention subscriptions: track seen record ids, across both queries, and wake only
23772
+ // for records not seen before, so a record both find wakes once, through the query that
23773
+ // reports it first.
23310
23774
  const currentSeen = this.seenMessages.get(sub.id) ?? new Set();
23311
23775
  const newMessages = [];
23312
- const terms = sub.terms ?? [];
23776
+ const provenance = new Map();
23313
23777
  for (const item of rows) {
23314
- // A SPARQL row names the record as `source`, a model row as `id`.
23315
- const address = sub.className ? item?.id : item?.source;
23778
+ const address = item?.id;
23316
23779
  if (typeof address !== "string" || !address || currentSeen.has(address))
23317
23780
  continue;
23318
- if (terms.length) {
23319
- // The mention query matched a substring; wake only on a whole word.
23320
- const text = Array.isArray(item.text) ? item.text.join(" ") : item.text;
23321
- if (typeof text !== "string" || !holdsAWholeWordTerm(text, terms)) {
23322
- this.logger.debug(`[waker] ${sub.id}: ${address} holds no term as a whole word, skipping`);
23323
- continue;
23324
- }
23781
+ // A mention link as it is; the text, a whole word only.
23782
+ const mention = mentionOf(item, sub);
23783
+ if (!mention) {
23784
+ this.logger.debug(`[waker] ${sub.id}: ${address} has no verified mention link and no term as a whole word, skipping`);
23785
+ continue;
23325
23786
  }
23326
23787
  currentSeen.add(address);
23327
23788
  newMessages.push(address);
23789
+ provenance.set(address, mention);
23328
23790
  }
23329
23791
  if (newMessages.length === 0) {
23330
23792
  this.logger.info(`[waker] ${sub.id}: no new mention among ${rows.length} items, skipping`);
@@ -23349,7 +23811,7 @@ class WakerSubscriptionManager {
23349
23811
  const ancestors = await this.ancestorsOf(sub, msgAddr, parents);
23350
23812
  this.logger.info(`[waker] ${sub.id}: message ${msgAddr} has ${parents.length} parent(s): ${parents.join(", ")}` +
23351
23813
  (ancestors.length ? `; ancestors: ${ancestors.join(", ")}` : ""));
23352
- mentions.push({ address: msgAddr, parents, ancestors });
23814
+ mentions.push({ address: msgAddr, parents, ancestors, ...provenance.get(msgAddr) });
23353
23815
  }
23354
23816
  this.seenMessages.set(sub.id, currentSeen);
23355
23817
  const pending = this.undelivered.get(sub.id) ?? new Map();
@@ -23375,20 +23837,24 @@ class WakerSubscriptionManager {
23375
23837
  }
23376
23838
  };
23377
23839
  proxy.onResult((result) => handleResult(result));
23840
+ mentionProxy?.onResult((result) => handleResult(result, false, " (mention query)"));
23841
+ for (const p of proxies) {
23842
+ p.onStatus?.((status) => this.onReopenStatus(sub, proxies, p, status));
23843
+ }
23378
23844
  if (this.isStale(sub.id, token)) {
23379
- try {
23380
- proxy.dispose();
23381
- }
23382
- catch { }
23845
+ disposeProxies();
23383
23846
  return;
23384
23847
  }
23385
- this.proxies.set(sub.id, proxy);
23848
+ this.proxies.set(sub.id, proxies);
23386
23849
  this.activeSubscriptions.set(sub.id, sub);
23387
23850
  // After a restart this wakes on mentions written while the waker was down; on a new
23388
- // subscription it records the existing ones as history.
23389
- if (proxy.result !== undefined) {
23851
+ // subscription it records the existing ones as history. The mention query's first, so a
23852
+ // record both hold wakes through its mention link.
23853
+ for (const [p, of] of [[mentionProxy, " (mention query)"], [proxy, ""]]) {
23854
+ if (p?.result === undefined)
23855
+ continue;
23390
23856
  try {
23391
- await handleResult(proxy.result, true);
23857
+ await handleResult(p.result, true, of);
23392
23858
  }
23393
23859
  catch (e) {
23394
23860
  this.logger.warn(`[waker] ${sub.id}: reading the opening result failed: ${e?.message ?? e}`);
@@ -23397,6 +23863,51 @@ class WakerSubscriptionManager {
23397
23863
  this.persist();
23398
23864
  this.logger.info(`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`);
23399
23865
  }
23866
+ /**
23867
+ * A proxy of `sub` failed to re-open its live query, or re-opened it after
23868
+ * failing. `sub` counts as active again once none of its proxies is still
23869
+ * re-opening. `proxies` tells a status of a replaced subscription apart.
23870
+ */
23871
+ onReopenStatus(sub, proxies, proxy, status) {
23872
+ if (this.proxies.get(sub.id) !== proxies)
23873
+ return;
23874
+ if (status?.state === "reopening") {
23875
+ const entry = this.reopening.get(sub.id) ?? { sub, proxies: new Set() };
23876
+ entry.proxies.add(proxy);
23877
+ if (!this.reopening.has(sub.id)) {
23878
+ this.reopening.set(sub.id, entry);
23879
+ this.activeSubscriptions.delete(sub.id);
23880
+ 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`);
23881
+ }
23882
+ return;
23883
+ }
23884
+ if (status?.state !== "open")
23885
+ return;
23886
+ const entry = this.reopening.get(sub.id);
23887
+ if (!entry)
23888
+ return;
23889
+ entry.proxies.delete(proxy);
23890
+ if (entry.proxies.size > 0)
23891
+ return;
23892
+ this.reopening.delete(sub.id);
23893
+ this.activeSubscriptions.set(sub.id, sub);
23894
+ this.logger.info(`[waker] ${sub.id}: live query re-opened, listening again`);
23895
+ // Wakes held back while it was not active go out now, not with the next mention.
23896
+ if (this.undelivered.get(sub.id)?.size)
23897
+ this.scheduleMentionWake(sub, proxy.result, this.debounceMs);
23898
+ }
23899
+ /** The wait before the next re-attempt round: `retryPendingMs` doubled per
23900
+ * round in a row that left something pending, capped at
23901
+ * `maxRetryPendingMs`, and between half and all of that, so wakers of a
23902
+ * restarted executor do not all retry at once. */
23903
+ nextRetryDelay() {
23904
+ const ceiling = this.retryCeiling();
23905
+ return ceiling / 2 + Math.random() * (ceiling / 2);
23906
+ }
23907
+ /** The longest the next re-attempt round waits. */
23908
+ retryCeiling() {
23909
+ return Math.min(this.retryPendingMs * 2 ** this.retryRounds, this.maxRetryPendingMs);
23910
+ }
23400
23911
  /** Arm the re-attempt timer if pending subscriptions are waiting. */
23401
23912
  scheduleRetry() {
23402
23913
  if (this.retryPendingMs <= 0)
@@ -23405,8 +23916,9 @@ class WakerSubscriptionManager {
23405
23916
  return;
23406
23917
  this.retryTimer = setTimeout(() => {
23407
23918
  this.retryTimer = null;
23919
+ this.retryRounds++;
23408
23920
  void this.retryPending();
23409
- }, this.retryPendingMs);
23921
+ }, this.nextRetryDelay());
23410
23922
  if (typeof this.retryTimer.unref === "function")
23411
23923
  this.retryTimer.unref();
23412
23924
  }
@@ -23440,27 +23952,39 @@ class WakerSubscriptionManager {
23440
23952
  }
23441
23953
  }
23442
23954
  }
23443
- /** Subscriptions that were rejected and are waiting to be re-attempted. */
23955
+ /** Subscriptions that are not listening and are being re-attempted: the
23956
+ * ones the executor rejected, and active ones whose live query is
23957
+ * re-opening after a reconnect. */
23444
23958
  getPending() {
23445
- return Array.from(this.pendingSubscriptions.values());
23959
+ return [
23960
+ ...this.pendingSubscriptions.values(),
23961
+ ...Array.from(this.reopening.values(), (entry) => entry.sub),
23962
+ ];
23446
23963
  }
23447
23964
  /**
23448
23965
  * Dispose a single subscription.
23449
23966
  * @param persist — if false, skip calling onPersist (used during batch cleanup).
23450
23967
  */
23451
23968
  dispose(id, persist = true) {
23969
+ this.release(id, persist);
23970
+ if (this.pendingSubscriptions.size === 0)
23971
+ this.retryRounds = 0;
23972
+ }
23973
+ /** Drop everything held for `id`, as `dispose()` does, but leave the
23974
+ * re-attempt backoff as it is. */
23975
+ release(id, persist) {
23452
23976
  // Invalidate any subscribe() for this id that is still awaiting.
23453
23977
  this.generations.set(id, (this.generations.get(id) ?? 0) + 1);
23454
- const proxy = this.proxies.get(id);
23455
- if (proxy) {
23978
+ for (const proxy of this.proxies.get(id) ?? []) {
23456
23979
  try {
23457
- proxy.dispose();
23980
+ proxy.dispose({ cancelOpening: true });
23458
23981
  }
23459
23982
  catch {
23460
23983
  /* ignore */
23461
23984
  }
23462
- this.proxies.delete(id);
23463
23985
  }
23986
+ this.proxies.delete(id);
23987
+ this.reopening.delete(id);
23464
23988
  const timer = this.debounceTimers.get(id);
23465
23989
  if (timer) {
23466
23990
  clearTimeout(timer);
@@ -23533,6 +24057,8 @@ class WakerSubscriptionManager {
23533
24057
  this.dispose(id, false);
23534
24058
  }
23535
24059
  this.pendingSubscriptions.clear();
24060
+ this.reopening.clear();
24061
+ this.retryRounds = 0;
23536
24062
  if (this.retryTimer) {
23537
24063
  clearTimeout(this.retryTimer);
23538
24064
  this.retryTimer = null;
@@ -23592,7 +24118,9 @@ class WakerSubscriptionManager {
23592
24118
  for (const [id, set] of this.delivered) {
23593
24119
  seen[id] = Array.from(set);
23594
24120
  }
23595
- this.onPersist(this.getActive(), seen);
24121
+ // A subscription that is re-opening was enrolled and is coming back: a
24122
+ // restart in the meantime must restore it.
24123
+ this.onPersist([...this.getActive(), ...Array.from(this.reopening.values(), (entry) => entry.sub)], seen);
23596
24124
  }
23597
24125
  }
23598
24126
  }
@@ -24037,4 +24565,4 @@ const SCOPED_EVENTS = new Set([
24037
24565
  "flow-state-changed",
24038
24566
  ]);
24039
24567
 
24040
- export { ACCEPTED_BY_GETTER, AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, AutoProcessorConfig, BelongsToMany, BelongsToOne, CALL_PROTOCOL_VERSION, Capability, CapabilityInput, ComputeLogEntry, Container, DEFAULT_ICE_SERVERS, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, FlowInstance, FlowInstanceRecord, FlowTransitionProposal, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, InterpretationOverlay, InterpretationRun, LONG_METHODS, LONG_TIMEOUT_MS, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LiveQuery, LocalModel, LocalModelInput, MENTION_TEXT_LIMIT, MeshManager, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PROPOSER_GETTER, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, READ_METHODS, ReadOnly, Resource, ResourceInput, RpcError, RuntimeInfo, SCOPED_EVENTS, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TextContent, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, applyUpdate, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, createTelepresenceChannel, determineNamespace, determinePredicate, effectiveLiteralStorage, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, hintFor, holdsAWholeWordTerm, ifExpr, invalidatePerspectiveCache, isArrayType, isContainedScope, isContainmentTraversal, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, isTraverseScope, linkEqual, linkExpressionInputToWire, linkExpressionToWire, linkMutationsToWire, literal, looksLikeUri, neighbourhoodExpressionFromWire, normalizeNamespaceString, normalizeSchemaType, normalizeValue, normalizeWhereForSparql, parseCallMessage, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, requireSingleParent, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString, valueToLiteralIri };
24568
+ export { ACCEPTED_BY_GETTER, AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, AutoProcessorConfig, BelongsToMany, BelongsToOne, CALL_PROTOCOL_VERSION, Capability, CapabilityInput, ComputeLogEntry, Container, DEFAULT_ICE_SERVERS, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, FlowInstance, FlowInstanceRecord, FlowTransitionProposal, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, InterpretationOverlay, InterpretationRun, LONG_METHODS, LONG_TIMEOUT_MS, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LiveQuery, LocalModel, LocalModelInput, MENTION_TEXT_LIMIT, Mentioning, MeshManager, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PROPOSER_GETTER, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, READ_METHODS, REOPEN_BASE_DELAY_MS, REOPEN_MAX_DELAY_MS, ReadOnly, Resource, ResourceInput, RpcError, RuntimeInfo, SCOPED_EVENTS, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TextContent, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, applyUpdate, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, createTelepresenceChannel, determineNamespace, determinePredicate, effectiveLiteralStorage, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, hintFor, holdsAWholeWordTerm, ifExpr, invalidatePerspectiveCache, isArrayType, isContainedScope, isContainmentTraversal, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, isTraverseScope, linkEqual, linkExpressionInputToWire, linkExpressionToWire, linkMutationsToWire, literal, looksLikeUri, mentionOf, neighbourhoodExpressionFromWire, normalizeNamespaceString, normalizeSchemaType, normalizeValue, normalizeWhereForSparql, parseCallMessage, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, reopenDelay, requireSingleParent, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString, valueToLiteralIri };