@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
@@ -5,6 +5,9 @@
5
5
  * running them once or subscribing to real-time updates.
6
6
  */
7
7
  import { LiveQuery } from "../perspectives/LiveQuery";
8
+ /** What a subscription compares to skip a callback whose results equal the
9
+ * last ones emitted (a resync or a reconnect re-open of an unchanged result). */
10
+ const fingerprint = (value) => JSON.stringify(value, (_, v) => (typeof v === 'function' ? undefined : v));
8
11
  /** Query builder for Ad4mModel queries.
9
12
  * Allows building queries with a fluent interface and either running them once
10
13
  * or subscribing to updates.
@@ -59,6 +62,10 @@ export class ModelQueryBuilder {
59
62
  }
60
63
  return this.ctor.parseModelResult(this.perspective, raw, include, properties);
61
64
  }
65
+ /** Snapshot instances for dirty tracking, as `execute` does for its rows. */
66
+ takeSnapshots(instances) {
67
+ this.ctor.takeSnapshots(instances, this.queryParams.include);
68
+ }
62
69
  /** Ends the current subscription, if any, on the client and the executor. */
63
70
  dispose() {
64
71
  if (this.currentSubscription) {
@@ -428,7 +435,6 @@ export class ModelQueryBuilder {
428
435
  this.dispose();
429
436
  const parseResults = (raw) => this.parse(raw);
430
437
  // Suppress callbacks whose parsed results equal the last ones emitted.
431
- const fingerprint = (results) => JSON.stringify(results, (_, v) => (typeof v === 'function' ? undefined : v));
432
438
  let lastFingerprint = null;
433
439
  const { initial } = await this.live(this.queryParams, (raw) => {
434
440
  try {
@@ -579,73 +585,46 @@ export class ModelQueryBuilder {
579
585
  *
580
586
  */
581
587
  async paginateSubscribe(pageSize, pageNumber, callback) {
582
- // Clean up any existing subscription
583
588
  this.dispose();
584
- // Subscribe to the full result set (no limit/offset) so the subscription
585
- // detects changes anywhere in the dataset; each change re-reads the page.
586
- const subscriptionParams = { ...(this.queryParams || {}) };
587
- delete subscriptionParams.limit;
588
- delete subscriptionParams.offset;
589
- // Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)
589
+ // Subscribe to the page itself. Since #1237 the executor re-runs a paged
590
+ // subscription when a record outside the page starts or stops matching
591
+ // (the `joins` and `scan` trigger rules), and a model result carries
592
+ // `totalCount`, so a write outside the page still changes the result and
593
+ // is pushed. Each page is built from the pushed rows: no second query, and
594
+ // the executor hydrates one page per change rather than every match.
595
+ // Pushes arrive in revision order, so the last callback is the latest
596
+ // state (#1051). After dispose() the live query delivers nothing.
590
597
  const paginatedQuery = {
591
598
  ...(this.queryParams || {}),
592
599
  limit: pageSize,
593
600
  offset: pageSize * (pageNumber - 1),
594
601
  count: true,
595
602
  };
596
- // One read in flight. A dispatch while a read is running sets `pending`
597
- // so a fetch always completes after the last dispatch. The generation
598
- // counter from #1020 dropped superseded fetches, but ordered them by
599
- // start time rather than by how fresh the data they read was — two
600
- // back-to-back dispatches could keep the fetch that saw 1 model and
601
- // drop the one that saw 2, after which the server has nothing further
602
- // to say (issue #1051 / CI: "Paginate callback did not see second model save").
603
- // After dispose() no read starts and no result is delivered, including
604
- // a read that was already in flight when dispose() ran.
605
- let disposed = false;
606
- let fetching = false;
607
- let pending = false;
608
- const processResults = async () => {
609
- if (disposed)
610
- return;
611
- if (fetching) {
612
- pending = true;
613
- return;
614
- }
615
- fetching = true;
603
+ // As subscribe(): a callback fires only when the rows or totalCount
604
+ // differ from the last page emitted, not on a resync or a reconnect
605
+ // re-open of an unchanged page.
606
+ let lastFingerprint = null;
607
+ const toPage = (raw) => {
608
+ const results = this.parse(raw);
609
+ const fp = fingerprint([results, raw?.totalCount]);
610
+ this.takeSnapshots(results);
611
+ return { page: { results, totalCount: raw?.totalCount, pageSize, pageNumber }, fp };
612
+ };
613
+ const { initial } = await this.live(paginatedQuery, (raw) => {
616
614
  try {
617
- const { results, totalCount } = await this.execute(paginatedQuery);
618
- if (!disposed)
619
- callback({ results, totalCount, pageSize, pageNumber });
615
+ const { page, fp } = toPage(raw);
616
+ if (fp === lastFingerprint)
617
+ return;
618
+ lastFingerprint = fp;
619
+ callback(page);
620
620
  }
621
- finally {
622
- fetching = false;
623
- if (pending) {
624
- pending = false;
625
- // Detached from the caller's promise: needs its own handler, or a
626
- // rejection here is unhandled.
627
- processResults().catch(e => console.error('Paginate subscription error:', e));
628
- }
621
+ catch (e) {
622
+ console.error('Paginate subscription error:', e);
629
623
  }
630
- };
631
- const { live } = await this.live(subscriptionParams, () => {
632
- processResults().catch(e => console.error('Paginate subscription error:', e));
633
624
  });
634
- if (this.currentSubscription === live) {
635
- this.currentSubscription = {
636
- dispose: () => {
637
- disposed = true;
638
- live.dispose();
639
- },
640
- };
641
- }
642
- else {
643
- // Disposed, or overtaken by a later subscribe, while opening: deliver nothing.
644
- disposed = true;
645
- }
646
- // Initial fetch (single call with count: true)
647
- const { results, totalCount } = await this.execute(paginatedQuery);
648
- return { results, totalCount, pageSize, pageNumber };
625
+ const { page, fp } = toPage(initial);
626
+ lastFingerprint = fp;
627
+ return page;
649
628
  }
650
629
  /**
651
630
  * Subscribes to paginated results updates using SPARQL.
@@ -484,6 +484,12 @@ export interface LinkRow {
484
484
  valid: boolean;
485
485
  invalid: boolean;
486
486
  };
487
+ /**
488
+ * Where this executor holds the link, spelled as `perspective.get()` spells
489
+ * it. Absent only when the store recorded none. Not signed: it says nothing
490
+ * about who wrote the link.
491
+ */
492
+ status?: "SHARED" | "LOCAL";
487
493
  }
488
494
  /** `instance.__links`: requested entry (spelled as requested) → its rows, oldest first. */
489
495
  export type LinksMap = Record<string, LinkRow[]>;
@@ -101,6 +101,10 @@ export declare class SfuManager {
101
101
  private rosterUnsubscribe;
102
102
  private dataChannelUnsubscribe;
103
103
  private disconnectedTimer;
104
+ /** Running while the room's roster leaves this agent out: see `noticeRoster`. */
105
+ private unlistedTimer;
106
+ /** How long the roster may leave this agent out before the call is rebuilt. */
107
+ private static readonly UNLISTED_GRACE_MS;
104
108
  constructor(neighbourhood: SfuNeighbourhoodApi, roomId: string, agentDid: string, neighbourhoodUrl?: string, iceConfig?: SfuIceConfig, sfuConfig?: SfuConfig);
105
109
  /**
106
110
  * Rebuild the call after its connection failed: leave, then join again
@@ -121,6 +125,17 @@ export declare class SfuManager {
121
125
  join(localStream: MediaStream): Promise<void>;
122
126
  /** Drop the server-event subscriptions of the current join. */
123
127
  private releaseServerEvents;
128
+ private clearUnlistedTimer;
129
+ /**
130
+ * The room's roster no longer lists this agent while `pc` is the call's:
131
+ * the server has dropped this session, and ICE may not say so. In E6
132
+ * (CI job 53158) one of six sessions never started a rebuild after a
133
+ * 20 s outage the server had dropped it for. Rebuild once the roster has
134
+ * left this agent out for `UNLISTED_GRACE_MS`; a roster that lists it
135
+ * again in that time cancels, since one published just before this
136
+ * join landed can arrive after it.
137
+ */
138
+ private noticeRoster;
124
139
  /** Undo a join that failed part way: its subscription and its connection. */
125
140
  private abandon;
126
141
  /**
@@ -82,6 +82,8 @@ export class SfuManager {
82
82
  this.rosterUnsubscribe = null;
83
83
  this.dataChannelUnsubscribe = null;
84
84
  this.disconnectedTimer = null;
85
+ /** Running while the room's roster leaves this agent out: see `noticeRoster`. */
86
+ this.unlistedTimer = null;
85
87
  this.neighbourhood = neighbourhood;
86
88
  this.neighbourhoodUrl = neighbourhoodUrl || "";
87
89
  this.roomId = roomId;
@@ -368,6 +370,37 @@ export class SfuManager {
368
370
  this.renegotiationUnsubscribe = null;
369
371
  this.rosterUnsubscribe?.();
370
372
  this.rosterUnsubscribe = null;
373
+ this.clearUnlistedTimer();
374
+ }
375
+ clearUnlistedTimer() {
376
+ if (this.unlistedTimer) {
377
+ clearTimeout(this.unlistedTimer);
378
+ this.unlistedTimer = null;
379
+ }
380
+ }
381
+ /**
382
+ * The room's roster no longer lists this agent while `pc` is the call's:
383
+ * the server has dropped this session, and ICE may not say so. In E6
384
+ * (CI job 53158) one of six sessions never started a rebuild after a
385
+ * 20 s outage the server had dropped it for. Rebuild once the roster has
386
+ * left this agent out for `UNLISTED_GRACE_MS`; a roster that lists it
387
+ * again in that time cancels, since one published just before this
388
+ * join landed can arrive after it.
389
+ */
390
+ noticeRoster(pc, dids) {
391
+ if (dids.includes(this.agentDid)) {
392
+ this.clearUnlistedTimer();
393
+ return;
394
+ }
395
+ if (this.unlistedTimer)
396
+ return;
397
+ this.unlistedTimer = setTimeout(() => {
398
+ this.unlistedTimer = null;
399
+ if (this.state.peerConnection !== pc)
400
+ return;
401
+ console.info("SFU: the room no longer lists this session, rebuilding the call");
402
+ void this.reconnect();
403
+ }, SfuManager.UNLISTED_GRACE_MS);
371
404
  }
372
405
  /** Undo a join that failed part way: its subscription and its connection. */
373
406
  abandon(pc) {
@@ -402,8 +435,10 @@ export class SfuManager {
402
435
  if (!ours(roster) || this.state.peerConnection !== pc)
403
436
  return;
404
437
  void joined.then(() => {
405
- if (this.state.peerConnection === pc)
406
- this.applyRoster(roster.participants, true);
438
+ if (this.state.peerConnection !== pc)
439
+ return;
440
+ this.applyRoster(roster.participants, true);
441
+ this.noticeRoster(pc, roster.participants);
407
442
  });
408
443
  });
409
444
  for (const unsubscribe of previous)
@@ -617,3 +652,5 @@ SfuManager.MAX_RECONNECTS = 3;
617
652
  SfuManager.REJOIN_WINDOW_MS = 120000;
618
653
  /** How long ICE may stay disconnected before a rebuild: the executor's `ICE_DISCONNECT_GRACE`. */
619
654
  SfuManager.DISCONNECT_GRACE_MS = 10000;
655
+ /** How long the roster may leave this agent out before the call is rebuilt. */
656
+ SfuManager.UNLISTED_GRACE_MS = 3000;
@@ -26,6 +26,27 @@ export interface QueryUpdate {
26
26
  export interface QueryLagged {
27
27
  lagged: true;
28
28
  }
29
+ /** What a live query tells its owner about re-opening its subscription after a
30
+ * reconnect or a failed resync: `reopening` after each failed attempt, with
31
+ * the delay before the next one, and `open` once a re-open succeeds after
32
+ * one failed. Until then the query is not live, even though its last result
33
+ * is still readable. */
34
+ export type LiveQueryStatus = {
35
+ state: 'reopening';
36
+ error: unknown;
37
+ retryInMs: number;
38
+ } | {
39
+ state: 'open';
40
+ };
41
+ /** Delay before the first retry of a failed re-open; it doubles per failure. */
42
+ export declare const REOPEN_BASE_DELAY_MS = 1000;
43
+ /** Longest delay between two re-open attempts. */
44
+ export declare const REOPEN_MAX_DELAY_MS = 60000;
45
+ /** The delay before re-open attempt `failures + 1`: between half and all of
46
+ * `REOPEN_BASE_DELAY_MS * 2^(failures - 1)`, capped at
47
+ * `REOPEN_MAX_DELAY_MS`. The random half spreads the clients of a restarted
48
+ * executor apart. */
49
+ export declare function reopenDelay(failures: number, random?: () => number): number;
29
50
  /** Apply one update to the last result. Query rows are a multiset: added rows are appended.
30
51
  * Throws when the update names an instance that neither the last result nor
31
52
  * the update holds: the last result was wrong, and the caller must resync. */
@@ -34,16 +55,31 @@ export declare function applyUpdate(result: any, update: QueryUpdate): any;
34
55
  * One live query on the executor. Holds the last result, applies each update
35
56
  * to it, calls `resyncSubscription` when a revision is missing, and opens a
36
57
  * new subscription after a reconnect (the executor ends a socket's
37
- * subscriptions when it closes). `onResult` gets every result after the
38
- * first; `start()` returns the first.
58
+ * subscriptions when it closes). A re-open that fails (the executor is
59
+ * still loading the perspective after a restart) is retried with backoff
60
+ * until it succeeds or the query is disposed; `onStatus` listeners hear
61
+ * about it (#1595). `onResult` gets every result after the first; `start()`
62
+ * returns the first.
39
63
  */
40
64
  export declare class LiveQuery {
41
65
  #private;
42
- constructor(client: PerspectiveClient, uuid: string, open: () => Promise<Subscribed>, onResult: (result: any) => void);
66
+ /** `open` subscribes on the executor; aborting its signal cancels the call. */
67
+ constructor(client: PerspectiveClient, uuid: string, open: (signal: AbortSignal) => Promise<Subscribed>, onResult: (result: any) => void);
43
68
  get id(): string | undefined;
44
69
  get result(): any;
70
+ /** Whether a re-open failed and the query is waiting to retry it. */
71
+ get reopening(): boolean;
72
+ /** Call `listener` on each failed re-open and when a re-open succeeds
73
+ * after one failed. Returns a remover. */
74
+ onStatus(listener: (status: LiveQueryStatus) => void): () => void;
45
75
  /** Open the subscription (again) and return its initial result. A start
46
76
  * that a newer one overtakes resolves with the newer one's result. */
47
77
  start(): Promise<any>;
48
- dispose(): void;
78
+ /** End the subscription. With `cancelOpening`, a subscribe call still in
79
+ * flight is cancelled too, so the executor stops computing a first result
80
+ * nobody waits for (#1595); the pending `start()` then rejects instead of
81
+ * resolving with that result. */
82
+ dispose(options?: {
83
+ cancelOpening?: boolean;
84
+ }): void;
49
85
  }
@@ -9,7 +9,19 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  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");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- 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;
12
+ 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;
13
+ /** Delay before the first retry of a failed re-open; it doubles per failure. */
14
+ export const REOPEN_BASE_DELAY_MS = 1000;
15
+ /** Longest delay between two re-open attempts. */
16
+ export const REOPEN_MAX_DELAY_MS = 60000;
17
+ /** The delay before re-open attempt `failures + 1`: between half and all of
18
+ * `REOPEN_BASE_DELAY_MS * 2^(failures - 1)`, capped at
19
+ * `REOPEN_MAX_DELAY_MS`. The random half spreads the clients of a restarted
20
+ * executor apart. */
21
+ export function reopenDelay(failures, random = Math.random) {
22
+ const ceiling = Math.min(REOPEN_BASE_DELAY_MS * 2 ** Math.max(0, failures - 1), REOPEN_MAX_DELAY_MS);
23
+ return ceiling / 2 + random() * ceiling / 2;
24
+ }
13
25
  /** Apply one update to the last result. Query rows are a multiset: added rows are appended.
14
26
  * Throws when the update names an instance that neither the last result nor
15
27
  * the update holds: the last result was wrong, and the caller must resync. */
@@ -46,10 +58,14 @@ export function applyUpdate(result, update) {
46
58
  * One live query on the executor. Holds the last result, applies each update
47
59
  * to it, calls `resyncSubscription` when a revision is missing, and opens a
48
60
  * new subscription after a reconnect (the executor ends a socket's
49
- * subscriptions when it closes). `onResult` gets every result after the
50
- * first; `start()` returns the first.
61
+ * subscriptions when it closes). A re-open that fails (the executor is
62
+ * still loading the perspective after a restart) is retried with backoff
63
+ * until it succeeds or the query is disposed; `onStatus` listeners hear
64
+ * about it (#1595). `onResult` gets every result after the first; `start()`
65
+ * returns the first.
51
66
  */
52
67
  export class LiveQuery {
68
+ /** `open` subscribes on the executor; aborting its signal cancels the call. */
53
69
  constructor(client, uuid, open, onResult) {
54
70
  _LiveQuery_instances.add(this);
55
71
  _LiveQuery_client.set(this, void 0);
@@ -67,45 +83,73 @@ export class LiveQuery {
67
83
  _LiveQuery_buffer.set(this, null);
68
84
  _LiveQuery_unlisten.set(this, void 0);
69
85
  _LiveQuery_unreconnect.set(this, void 0);
86
+ // Aborts the subscribe call still in flight, for `dispose({ cancelOpening })`.
87
+ _LiveQuery_opening.set(this, void 0);
88
+ _LiveQuery_retryTimer.set(this, void 0);
89
+ _LiveQuery_reopening.set(this, false);
90
+ _LiveQuery_statusListeners.set(this, new Set()
91
+ /** `open` subscribes on the executor; aborting its signal cancels the call. */
92
+ );
70
93
  __classPrivateFieldSet(this, _LiveQuery_client, client, "f");
71
94
  __classPrivateFieldSet(this, _LiveQuery_uuid, uuid, "f");
72
95
  __classPrivateFieldSet(this, _LiveQuery_open, open, "f");
73
96
  __classPrivateFieldSet(this, _LiveQuery_onResult, onResult, "f");
74
97
  __classPrivateFieldSet(this, _LiveQuery_unlisten, client.onQueryUpdate(update => __classPrivateFieldGet(this, _LiveQuery_instances, "m", _LiveQuery_receive).call(this, update)), "f");
75
- __classPrivateFieldSet(this, _LiveQuery_unreconnect, client.onReconnect(() => {
76
- this.start().catch(e => console.error('Error re-opening live query after reconnect:', e));
77
- }), "f");
98
+ __classPrivateFieldSet(this, _LiveQuery_unreconnect, client.onReconnect(() => __classPrivateFieldGet(this, _LiveQuery_instances, "m", _LiveQuery_reopen).call(this)), "f");
78
99
  }
79
100
  get id() { return __classPrivateFieldGet(this, _LiveQuery_id, "f"); }
80
101
  get result() { return __classPrivateFieldGet(this, _LiveQuery_result, "f"); }
102
+ /** Whether a re-open failed and the query is waiting to retry it. */
103
+ get reopening() { return __classPrivateFieldGet(this, _LiveQuery_reopening, "f"); }
104
+ /** Call `listener` on each failed re-open and when a re-open succeeds
105
+ * after one failed. Returns a remover. */
106
+ onStatus(listener) {
107
+ __classPrivateFieldGet(this, _LiveQuery_statusListeners, "f").add(listener);
108
+ return () => __classPrivateFieldGet(this, _LiveQuery_statusListeners, "f").delete(listener);
109
+ }
81
110
  /** Open the subscription (again) and return its initial result. A start
82
111
  * that a newer one overtakes resolves with the newer one's result. */
83
112
  start() {
84
113
  var _a;
114
+ __classPrivateFieldGet(this, _LiveQuery_instances, "m", _LiveQuery_clearRetry).call(this);
85
115
  __classPrivateFieldSet(this, _LiveQuery_latest, __classPrivateFieldGet(this, _LiveQuery_instances, "m", _LiveQuery_start).call(this, __classPrivateFieldSet(this, _LiveQuery_generation, (_a = __classPrivateFieldGet(this, _LiveQuery_generation, "f"), ++_a), "f")), "f");
86
116
  return __classPrivateFieldGet(this, _LiveQuery_latest, "f");
87
117
  }
88
- dispose() {
118
+ /** End the subscription. With `cancelOpening`, a subscribe call still in
119
+ * flight is cancelled too, so the executor stops computing a first result
120
+ * nobody waits for (#1595); the pending `start()` then rejects instead of
121
+ * resolving with that result. */
122
+ dispose(options = {}) {
89
123
  var _a;
90
124
  __classPrivateFieldSet(this, _LiveQuery_disposed, true, "f");
91
125
  __classPrivateFieldSet(this, _LiveQuery_generation, (_a = __classPrivateFieldGet(this, _LiveQuery_generation, "f"), _a++, _a), "f");
126
+ __classPrivateFieldGet(this, _LiveQuery_instances, "m", _LiveQuery_clearRetry).call(this);
127
+ __classPrivateFieldGet(this, _LiveQuery_statusListeners, "f").clear();
92
128
  __classPrivateFieldGet(this, _LiveQuery_unlisten, "f").call(this);
93
129
  __classPrivateFieldGet(this, _LiveQuery_unreconnect, "f").call(this);
130
+ if (options.cancelOpening)
131
+ __classPrivateFieldGet(this, _LiveQuery_opening, "f")?.abort();
94
132
  if (__classPrivateFieldGet(this, _LiveQuery_id, "f"))
95
133
  __classPrivateFieldGet(this, _LiveQuery_client, "f").disposeQuerySubscription(__classPrivateFieldGet(this, _LiveQuery_uuid, "f"), __classPrivateFieldGet(this, _LiveQuery_id, "f")).catch(() => { });
96
134
  }
97
135
  }
98
- _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) {
136
+ _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) {
99
137
  __classPrivateFieldSet(this, _LiveQuery_buffer, [], "f");
138
+ const opening = new AbortController();
139
+ __classPrivateFieldSet(this, _LiveQuery_opening, opening, "f");
100
140
  let subscribed;
101
141
  try {
102
- subscribed = await __classPrivateFieldGet(this, _LiveQuery_open, "f").call(this);
142
+ subscribed = await __classPrivateFieldGet(this, _LiveQuery_open, "f").call(this, opening.signal);
103
143
  }
104
144
  catch (e) {
105
145
  if (generation === __classPrivateFieldGet(this, _LiveQuery_generation, "f"))
106
146
  __classPrivateFieldSet(this, _LiveQuery_buffer, null, "f");
107
147
  throw e;
108
148
  }
149
+ finally {
150
+ if (__classPrivateFieldGet(this, _LiveQuery_opening, "f") === opening)
151
+ __classPrivateFieldSet(this, _LiveQuery_opening, undefined, "f");
152
+ }
109
153
  if (__classPrivateFieldGet(this, _LiveQuery_disposed, "f") || generation !== __classPrivateFieldGet(this, _LiveQuery_generation, "f")) {
110
154
  __classPrivateFieldGet(this, _LiveQuery_client, "f").disposeQuerySubscription(__classPrivateFieldGet(this, _LiveQuery_uuid, "f"), subscribed.subscriptionId).catch(() => { });
111
155
  // Disposed while opening (e.g. a newer subscribe() on the same
@@ -115,6 +159,46 @@ _LiveQuery_client = new WeakMap(), _LiveQuery_uuid = new WeakMap(), _LiveQuery_o
115
159
  __classPrivateFieldSet(this, _LiveQuery_id, subscribed.subscriptionId, "f");
116
160
  __classPrivateFieldGet(this, _LiveQuery_instances, "m", _LiveQuery_replace).call(this, subscribed.revision, subscribed.result);
117
161
  return __classPrivateFieldGet(this, _LiveQuery_result, "f");
162
+ }, _LiveQuery_reopen = function _LiveQuery_reopen(failures = 0) {
163
+ if (__classPrivateFieldGet(this, _LiveQuery_disposed, "f"))
164
+ return;
165
+ const reopened = this.start();
166
+ const generation = __classPrivateFieldGet(this, _LiveQuery_generation, "f");
167
+ reopened.then(() => {
168
+ if (__classPrivateFieldGet(this, _LiveQuery_disposed, "f") || generation !== __classPrivateFieldGet(this, _LiveQuery_generation, "f") || !__classPrivateFieldGet(this, _LiveQuery_reopening, "f"))
169
+ return;
170
+ __classPrivateFieldSet(this, _LiveQuery_reopening, false, "f");
171
+ __classPrivateFieldGet(this, _LiveQuery_instances, "m", _LiveQuery_emit).call(this, { state: 'open' });
172
+ }, error => {
173
+ if (__classPrivateFieldGet(this, _LiveQuery_disposed, "f") || generation !== __classPrivateFieldGet(this, _LiveQuery_generation, "f"))
174
+ return;
175
+ const retryInMs = reopenDelay(failures + 1);
176
+ console.error(`Error re-opening live query (attempt ${failures + 1}), retrying in ${Math.round(retryInMs)}ms:`, error);
177
+ __classPrivateFieldSet(this, _LiveQuery_reopening, true, "f");
178
+ __classPrivateFieldGet(this, _LiveQuery_instances, "m", _LiveQuery_emit).call(this, { state: 'reopening', error, retryInMs });
179
+ const timer = setTimeout(() => {
180
+ __classPrivateFieldSet(this, _LiveQuery_retryTimer, undefined, "f");
181
+ __classPrivateFieldGet(this, _LiveQuery_instances, "m", _LiveQuery_reopen).call(this, failures + 1);
182
+ }, retryInMs);
183
+ // Node: a pending retry must not keep the process alive.
184
+ if (typeof timer?.unref === 'function')
185
+ timer.unref();
186
+ __classPrivateFieldSet(this, _LiveQuery_retryTimer, timer, "f");
187
+ });
188
+ }, _LiveQuery_clearRetry = function _LiveQuery_clearRetry() {
189
+ if (__classPrivateFieldGet(this, _LiveQuery_retryTimer, "f") === undefined)
190
+ return;
191
+ clearTimeout(__classPrivateFieldGet(this, _LiveQuery_retryTimer, "f"));
192
+ __classPrivateFieldSet(this, _LiveQuery_retryTimer, undefined, "f");
193
+ }, _LiveQuery_emit = function _LiveQuery_emit(status) {
194
+ for (const listener of [...__classPrivateFieldGet(this, _LiveQuery_statusListeners, "f")]) {
195
+ try {
196
+ listener(status);
197
+ }
198
+ catch (e) {
199
+ console.error('Error in live query status listener:', e);
200
+ }
201
+ }
118
202
  }, _LiveQuery_replace = function _LiveQuery_replace(revision, result) {
119
203
  __classPrivateFieldSet(this, _LiveQuery_revision, revision, "f");
120
204
  __classPrivateFieldSet(this, _LiveQuery_result, result, "f");
@@ -163,7 +247,7 @@ _LiveQuery_client = new WeakMap(), _LiveQuery_uuid = new WeakMap(), _LiveQuery_o
163
247
  // Replace the subscription with a new one.
164
248
  if (!__classPrivateFieldGet(this, _LiveQuery_disposed, "f") && generation === __classPrivateFieldGet(this, _LiveQuery_generation, "f")) {
165
249
  __classPrivateFieldGet(this, _LiveQuery_client, "f").disposeQuerySubscription(__classPrivateFieldGet(this, _LiveQuery_uuid, "f"), id).catch(() => { });
166
- this.start().catch(e => console.error('Error re-opening live query:', e));
250
+ __classPrivateFieldGet(this, _LiveQuery_instances, "m", _LiveQuery_reopen).call(this);
167
251
  }
168
252
  });
169
253
  };
@@ -0,0 +1,37 @@
1
+ import { Ad4mModel } from "../model/Ad4mModel";
2
+ /**
3
+ * The built-in abstract class `Mentioning { mentions }`: a record that
4
+ * mentions agents — a post, a message, a block of a document. `mentions` is
5
+ * a relation to their DIDs.
6
+ *
7
+ * Querying it reads every class that has a relation named `mentions`, or one
8
+ * aliased to `mentions`, under any predicate, whether or not the class has
9
+ * text. A class whose relation has another name aliases it:
10
+ *
11
+ * ```typescript
12
+ * @Model({ name: "Note", implements: [Mentioning] })
13
+ * class Note extends Ad4mModel {
14
+ * @HasMany({ through: "app://cc", alias: { Mentioning: "mentions" } })
15
+ * cc: string[] = [];
16
+ * }
17
+ *
18
+ * const mentioningMe = await Mentioning.findAll(perspective, { where: { mentions: myDid } });
19
+ * ```
20
+ *
21
+ * The waker's mention subscription (`get_mention_waker_config`) reads it: a
22
+ * record whose `mentions` links the agent's DID, in a link another agent
23
+ * wrote, wakes the agent whatever its text says. Names in text it reads
24
+ * through {@link TextContent}.
25
+ *
26
+ * Built in: the executor declares it (mirrors
27
+ * `rust-executor/src/perspectives/hardwired_sdna/mentioning.json`) and reads
28
+ * it by its URI, `ad4m://Mentioning`, so a perspective never stores it and an
29
+ * app class named `Mentioning` does not replace it. `register()` on it writes
30
+ * nothing.
31
+ */
32
+ export declare class Mentioning extends Ad4mModel {
33
+ /** The URI the executor reads it by. */
34
+ static readonly builtinUri = "ad4m://Mentioning";
35
+ /** The agents (DIDs) the record mentions. */
36
+ mentions: string[];
37
+ }
@@ -0,0 +1,58 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ 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;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { Ad4mModel } from "../model/Ad4mModel";
11
+ import { HasMany, Model } from "../model/decorators";
12
+ /**
13
+ * The built-in abstract class `Mentioning { mentions }`: a record that
14
+ * mentions agents — a post, a message, a block of a document. `mentions` is
15
+ * a relation to their DIDs.
16
+ *
17
+ * Querying it reads every class that has a relation named `mentions`, or one
18
+ * aliased to `mentions`, under any predicate, whether or not the class has
19
+ * text. A class whose relation has another name aliases it:
20
+ *
21
+ * ```typescript
22
+ * @Model({ name: "Note", implements: [Mentioning] })
23
+ * class Note extends Ad4mModel {
24
+ * @HasMany({ through: "app://cc", alias: { Mentioning: "mentions" } })
25
+ * cc: string[] = [];
26
+ * }
27
+ *
28
+ * const mentioningMe = await Mentioning.findAll(perspective, { where: { mentions: myDid } });
29
+ * ```
30
+ *
31
+ * The waker's mention subscription (`get_mention_waker_config`) reads it: a
32
+ * record whose `mentions` links the agent's DID, in a link another agent
33
+ * wrote, wakes the agent whatever its text says. Names in text it reads
34
+ * through {@link TextContent}.
35
+ *
36
+ * Built in: the executor declares it (mirrors
37
+ * `rust-executor/src/perspectives/hardwired_sdna/mentioning.json`) and reads
38
+ * it by its URI, `ad4m://Mentioning`, so a perspective never stores it and an
39
+ * app class named `Mentioning` does not replace it. `register()` on it writes
40
+ * nothing.
41
+ */
42
+ let Mentioning = class Mentioning extends Ad4mModel {
43
+ constructor() {
44
+ super(...arguments);
45
+ /** The agents (DIDs) the record mentions. */
46
+ this.mentions = [];
47
+ }
48
+ };
49
+ /** The URI the executor reads it by. */
50
+ Mentioning.builtinUri = "ad4m://Mentioning";
51
+ __decorate([
52
+ HasMany({ through: "ad4m://mentions" }),
53
+ __metadata("design:type", Array)
54
+ ], Mentioning.prototype, "mentions", void 0);
55
+ Mentioning = __decorate([
56
+ Model({ name: "Mentioning", abstract: true })
57
+ ], Mentioning);
58
+ export { Mentioning };
@@ -11,6 +11,8 @@ import { LinkStatus, PerspectiveProxy } from './PerspectiveProxy';
11
11
  import { AIClient } from "../ai/AIClient";
12
12
  import type { QueryLagged, QueryUpdate, Subscribed } from "./LiveQuery";
13
13
  import type { TranscriptTurn } from "../generated/api";
14
+ import type { AgentMessage } from "../generated/api/AgentMessage";
15
+ import type { AgentReply } from "../generated/api/AgentReply";
14
16
  import type { JsonValue } from "../generated/api/serde_json/JsonValue";
15
17
  import type { AddAutoProcessorConfig, InterpretationOverlayInfo, RawScope, RunInterpretationObserveOptions } from "./AutoProcessor";
16
18
  import type { FlowFireOutcome, FlowMintedReceipt, FlowOutputRef, FlowProposeResult, FlowReceiptVerdict, FlowStateEntry, FlowValidOutput } from "./FlowInstance";
@@ -29,7 +31,8 @@ export declare class PerspectiveClient {
29
31
  queryProlog(uuid: string, query: string, options?: CallOptions): Promise<unknown>;
30
32
  querySparql<T = any>(uuid: string, query: string, options?: CallOptions): Promise<T>;
31
33
  /** Open a live SPARQL query. Updates arrive through {@link onQueryUpdate}. */
32
- subscribeQuery(uuid: string, query: string): Promise<Subscribed>;
34
+ /** `options.signal` cancels the call, and the executor stops computing the first result. */
35
+ subscribeQuery(uuid: string, query: string, options?: CallOptions): Promise<Subscribed>;
33
36
  /** Every `query-subscription-update` event on this client's socket. */
34
37
  onQueryUpdate(cb: (update: QueryUpdate | QueryLagged) => void): () => void;
35
38
  /** The current result and revision of a live query, after a revision gap. */
@@ -45,7 +48,8 @@ export declare class PerspectiveClient {
45
48
  subjectClassesOf(uuid: string, uris: string[]): Promise<Record<string, string[]>>;
46
49
  evaluateGetters(uuid: string, className: string, instanceIds: string[], propertyNames?: string[]): Promise<Record<string, Record<string, any>>>;
47
50
  /** Open a live model query over one class or several. Updates arrive through {@link onQueryUpdate}. */
48
- modelSubscribe(uuid: string, className: string | string[], queryJson: string): Promise<Subscribed>;
51
+ /** `options.signal` cancels the call, and the executor stops computing the first result. */
52
+ modelSubscribe(uuid: string, className: string | string[], queryJson: string, options?: CallOptions): Promise<Subscribed>;
49
53
  add(name: string): Promise<PerspectiveProxy>;
50
54
  update(uuid: string, name: string): Promise<PerspectiveProxy>;
51
55
  remove(uuid: string): Promise<{
@@ -86,6 +90,26 @@ export declare class PerspectiveClient {
86
90
  * Defaults to {@link LONG_TIMEOUT_MS}, like the single-shot path.
87
91
  */
88
92
  runInterpretationWithHarness(uuid: string, transcript: TranscriptTurn[], basePrefix: string, maxToolCalls: number, classes?: string[], modelOverride?: string, existingScope?: RawScope, observationId?: string, emitDebugEvents?: boolean, options?: CallOptions): Promise<string[]>;
93
+ /**
94
+ * A conversation with a model in this perspective, using the executor's own tools: the tools
95
+ * that read this perspective, and only the writing tools named in `writeTools`. Every tool a
96
+ * session offers acts on this perspective alone, so tools about other perspectives, the agent
97
+ * or the node (listing or publishing perspectives, the profile) are not available. Runs as the
98
+ * caller, with the caller's capabilities, and answers with the model's final reply.
99
+ *
100
+ * Defaults to {@link LONG_TIMEOUT_MS}: an agent may read documentation and make many tool
101
+ * calls before it answers.
102
+ */
103
+ runAgent(uuid: string, messages: AgentMessage[], settings?: {
104
+ /** What the person is looking at, as a hint for the model (`{ recordId }`). */
105
+ context?: Record<string, unknown>;
106
+ /** Tools that write which the model may call. Absent: the session only reads. */
107
+ writeTools?: string[];
108
+ /** A model id; the node's default language model when absent. */
109
+ model?: string;
110
+ /** How many tool calls before the model must answer. Default 20. */
111
+ maxToolCalls?: number;
112
+ }, options?: CallOptions): Promise<AgentReply>;
89
113
  /**
90
114
  * Register a neighbourhood auto-processor on this perspective. The executor's
91
115
  * watch loop then runs interpretation automatically over new source items