@coasys/ad4m 0.13.1-staging.1 → 0.13.1-staging.2

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 (222) hide show
  1. package/lib/index.cjs +3789 -1192
  2. package/lib/index.js +3783 -1193
  3. package/lib/src/generated/api/AgentsByDidsRequest.d.ts +3 -0
  4. package/lib/src/generated/api/CallSessionInfo.d.ts +23 -0
  5. package/lib/src/generated/api/DiscardBatchRequest.d.ts +3 -0
  6. package/lib/src/generated/api/Events.d.ts +13 -3
  7. package/lib/src/generated/api/Events.js +1 -0
  8. package/lib/src/generated/api/FlowStateChangedEvent.d.ts +38 -0
  9. package/lib/src/generated/api/FlowStateEntry.d.ts +18 -0
  10. package/lib/src/generated/api/FlowStateEntry.js +2 -0
  11. package/lib/src/generated/api/IceServer.d.ts +18 -0
  12. package/lib/src/generated/api/IceServer.js +2 -0
  13. package/lib/src/generated/api/OnlineAgent.d.ts +4 -0
  14. package/lib/src/generated/api/PerspectiveDiscardBatchParams.d.ts +4 -0
  15. package/lib/src/generated/api/PerspectiveDiscardBatchParams.js +2 -0
  16. package/lib/src/generated/api/PerspectiveFlowFiredParams.d.ts +8 -0
  17. package/lib/src/generated/api/PerspectiveFlowFiredParams.js +2 -0
  18. package/lib/src/generated/api/PerspectiveFlowStatesParams.d.ts +11 -0
  19. package/lib/src/generated/api/PerspectiveFlowStatesParams.js +2 -0
  20. package/lib/src/generated/api/PerspectiveGetAllShaclParams.d.ts +7 -0
  21. package/lib/src/generated/api/PerspectiveGetAllShaclParams.js +2 -0
  22. package/lib/src/generated/api/PerspectiveModelQueryParams.d.ts +6 -1
  23. package/lib/src/generated/api/PerspectiveRemoveSubjectParams.d.ts +6 -0
  24. package/lib/src/generated/api/PerspectiveRemoveSubjectParams.js +2 -0
  25. package/lib/src/generated/api/PerspectiveResynced.d.ts +8 -0
  26. package/lib/src/generated/api/PerspectiveResynced.js +2 -0
  27. package/lib/src/generated/api/PerspectiveSubscribed.d.ts +10 -0
  28. package/lib/src/generated/api/PerspectiveSubscribed.js +2 -0
  29. package/lib/src/generated/api/PerspectiveUpdateSubjectParams.d.ts +10 -0
  30. package/lib/src/generated/api/PerspectiveUpdateSubjectParams.js +2 -0
  31. package/lib/src/generated/api/QuerySubscriptionUpdate.d.ts +19 -0
  32. package/lib/src/generated/api/QuerySubscriptionUpdate.js +2 -0
  33. package/lib/src/generated/api/QuerySubscriptionUpdateEvent.d.ts +7 -0
  34. package/lib/src/generated/api/QuerySubscriptionUpdateEvent.js +1 -0
  35. package/lib/src/generated/api/QueryUpdatesLagged.d.ts +7 -0
  36. package/lib/src/generated/api/QueryUpdatesLagged.js +2 -0
  37. package/lib/src/generated/api/RemoveSubjectRequest.d.ts +9 -0
  38. package/lib/src/generated/api/RemoveSubjectRequest.js +2 -0
  39. package/lib/src/generated/api/ResyncSubscriptionRequest.d.ts +3 -0
  40. package/lib/src/generated/api/ResyncSubscriptionRequest.js +2 -0
  41. package/lib/src/generated/api/RpcMethods.d.ts +134 -14
  42. package/lib/src/generated/api/RpcMethods.js +12 -0
  43. package/lib/src/generated/api/SfuAddIceCandidateParams.d.ts +8 -0
  44. package/lib/src/generated/api/SfuAddIceCandidateParams.js +2 -0
  45. package/lib/src/generated/api/SfuAnswerServerOfferParams.d.ts +8 -0
  46. package/lib/src/generated/api/SfuAnswerServerOfferParams.js +2 -0
  47. package/lib/src/generated/api/SfuCallJoinParams.d.ts +14 -0
  48. package/lib/src/generated/api/SfuCallJoinParams.js +2 -0
  49. package/lib/src/generated/api/SfuCallRenegotiationOffer.d.ts +30 -0
  50. package/lib/src/generated/api/SfuCallRenegotiationOffer.js +1 -0
  51. package/lib/src/generated/api/SfuCascadePipe.d.ts +4 -0
  52. package/lib/src/generated/api/SfuCascadePipe.js +2 -0
  53. package/lib/src/generated/api/SfuCascadeStatus.d.ts +8 -0
  54. package/lib/src/generated/api/SfuCascadeStatus.js +1 -0
  55. package/lib/src/generated/api/SfuConfig.d.ts +52 -0
  56. package/lib/src/generated/api/SfuConfig.js +1 -0
  57. package/lib/src/generated/api/SfuDataMessage.d.ts +24 -0
  58. package/lib/src/generated/api/SfuDataMessage.js +2 -0
  59. package/lib/src/generated/api/SfuEnsureMembershipParams.d.ts +4 -0
  60. package/lib/src/generated/api/SfuEnsureMembershipParams.js +2 -0
  61. package/lib/src/generated/api/SfuMigrateEvent.d.ts +21 -0
  62. package/lib/src/generated/api/SfuMigrateEvent.js +2 -0
  63. package/lib/src/generated/api/SfuNeighbourhoodParams.d.ts +3 -0
  64. package/lib/src/generated/api/SfuNeighbourhoodParams.js +2 -0
  65. package/lib/src/generated/api/SfuParticipantQualityPreference.d.ts +7 -0
  66. package/lib/src/generated/api/SfuParticipantQualityPreference.js +2 -0
  67. package/lib/src/generated/api/SfuPerspectiveParams.d.ts +6 -0
  68. package/lib/src/generated/api/SfuPerspectiveParams.js +2 -0
  69. package/lib/src/generated/api/SfuQualityPreferenceParams.d.ts +8 -0
  70. package/lib/src/generated/api/SfuQualityPreferenceParams.js +2 -0
  71. package/lib/src/generated/api/SfuRoomInfo.d.ts +11 -0
  72. package/lib/src/generated/api/SfuRoomInfo.js +1 -0
  73. package/lib/src/generated/api/SfuRoomParams.d.ts +4 -0
  74. package/lib/src/generated/api/SfuRoomParams.js +2 -0
  75. package/lib/src/generated/api/SfuRoomParticipantInfo.d.ts +11 -0
  76. package/lib/src/generated/api/SfuRoomParticipantInfo.js +2 -0
  77. package/lib/src/generated/api/SfuRoomRoster.d.ts +13 -0
  78. package/lib/src/generated/api/SfuRoomRoster.js +2 -0
  79. package/lib/src/generated/api/SfuSendDataParams.d.ts +10 -0
  80. package/lib/src/generated/api/SfuSendDataParams.js +2 -0
  81. package/lib/src/generated/api/SfuSetConfigParams.d.ts +5 -0
  82. package/lib/src/generated/api/SfuSetConfigParams.js +1 -0
  83. package/lib/src/generated/api/SfuStatus.d.ts +24 -0
  84. package/lib/src/generated/api/SfuStatus.js +2 -0
  85. package/lib/src/generated/api/TrackMapEntry.d.ts +17 -0
  86. package/lib/src/generated/api/TrackMapEntry.js +2 -0
  87. package/lib/src/generated/api/UpdateSubjectRequest.d.ts +12 -0
  88. package/lib/src/generated/api/UpdateSubjectRequest.js +2 -0
  89. package/lib/src/generated/api/index.d.ts +3 -0
  90. package/lib/src/index.d.ts +7 -0
  91. package/lib/src/index.js +4 -0
  92. package/lib/src/model/Ad4mModel.d.ts +84 -0
  93. package/lib/src/model/Ad4mModel.js +234 -4
  94. package/lib/src/model/ModelQueryBuilder.d.ts +16 -35
  95. package/lib/src/model/ModelQueryBuilder.js +88 -270
  96. package/lib/src/model/decorators.d.ts +32 -0
  97. package/lib/src/model/decorators.js +40 -1
  98. package/lib/src/model/shacl-gen.d.ts +3 -1
  99. package/lib/src/model/shacl-gen.js +13 -1
  100. package/lib/src/model/types.d.ts +7 -0
  101. package/lib/src/neighbourhood/MeshManager.d.ts +384 -0
  102. package/lib/src/neighbourhood/MeshManager.js +1144 -0
  103. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +91 -0
  104. package/lib/src/neighbourhood/NeighbourhoodClient.js +196 -0
  105. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +55 -1
  106. package/lib/src/neighbourhood/NeighbourhoodProxy.js +170 -3
  107. package/lib/src/neighbourhood/Session.d.ts +105 -0
  108. package/lib/src/neighbourhood/Session.js +412 -0
  109. package/lib/src/neighbourhood/SfuManager.d.ts +174 -0
  110. package/lib/src/neighbourhood/SfuManager.js +619 -0
  111. package/lib/src/neighbourhood/SfuTypes.d.ts +35 -0
  112. package/lib/src/neighbourhood/SfuTypes.js +8 -0
  113. package/lib/src/perspectives/FlowInstance.d.ts +63 -24
  114. package/lib/src/perspectives/FlowInstance.js +74 -31
  115. package/lib/src/perspectives/FlowModels.d.ts +0 -16
  116. package/lib/src/perspectives/FlowModels.js +8 -16
  117. package/lib/src/perspectives/LiveQuery.d.ts +49 -0
  118. package/lib/src/perspectives/LiveQuery.js +169 -0
  119. package/lib/src/perspectives/PerspectiveClient.d.ts +24 -15
  120. package/lib/src/perspectives/PerspectiveClient.js +33 -36
  121. package/lib/src/perspectives/PerspectiveProxy.d.ts +67 -167
  122. package/lib/src/perspectives/PerspectiveProxy.js +121 -475
  123. package/lib/src/perspectives/TextContent.d.ts +31 -0
  124. package/lib/src/perspectives/TextContent.js +52 -0
  125. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +23 -0
  126. package/lib/src/perspectives/WakerSubscriptionManager.js +58 -17
  127. package/lib/src/shacl/SHACLFlow.d.ts +7 -4
  128. package/lib/src/shacl/SHACLFlow.js +7 -4
  129. package/lib/src/shacl/SHACLShape.d.ts +9 -0
  130. package/lib/src/shacl/SHACLShape.js +37 -0
  131. package/package.json +2 -2
  132. package/pnpm-workspace.yaml +4 -1
  133. package/src/Ad4mClient.test.ts +89 -17
  134. package/src/generated/api/AgentsByDidsRequest.ts +3 -0
  135. package/src/generated/api/CallSessionInfo.ts +20 -0
  136. package/src/generated/api/DiscardBatchRequest.ts +3 -0
  137. package/src/generated/api/Events.ts +14 -3
  138. package/src/generated/api/FlowStateChangedEvent.ts +36 -0
  139. package/src/generated/api/FlowStateEntry.ts +18 -0
  140. package/src/generated/api/IceServer.ts +19 -0
  141. package/src/generated/api/OnlineAgent.ts +6 -1
  142. package/src/generated/api/PerspectiveDiscardBatchParams.ts +3 -0
  143. package/src/generated/api/PerspectiveFlowFiredParams.ts +7 -0
  144. package/src/generated/api/PerspectiveFlowStatesParams.ts +11 -0
  145. package/src/generated/api/PerspectiveGetAllShaclParams.ts +6 -0
  146. package/src/generated/api/PerspectiveModelQueryParams.ts +5 -1
  147. package/src/generated/api/PerspectiveRemoveSubjectParams.ts +3 -0
  148. package/src/generated/api/PerspectiveResynced.ts +7 -0
  149. package/src/generated/api/PerspectiveSubscribed.ts +8 -0
  150. package/src/generated/api/PerspectiveUpdateSubjectParams.ts +7 -0
  151. package/src/generated/api/QuerySubscriptionUpdate.ts +10 -0
  152. package/src/generated/api/QuerySubscriptionUpdateEvent.ts +9 -0
  153. package/src/generated/api/QueryUpdatesLagged.ts +7 -0
  154. package/src/generated/api/RemoveSubjectRequest.ts +7 -0
  155. package/src/generated/api/ResyncSubscriptionRequest.ts +3 -0
  156. package/src/generated/api/RpcMethods.ts +68 -8
  157. package/src/generated/api/SfuAddIceCandidateParams.ts +7 -0
  158. package/src/generated/api/SfuAnswerServerOfferParams.ts +7 -0
  159. package/src/generated/api/SfuCallJoinParams.ts +13 -0
  160. package/src/generated/api/SfuCallRenegotiationOffer.ts +29 -0
  161. package/src/generated/api/SfuCascadePipe.ts +3 -0
  162. package/src/generated/api/SfuCascadeStatus.ts +7 -0
  163. package/src/generated/api/SfuConfig.ts +53 -0
  164. package/src/generated/api/SfuDataMessage.ts +23 -0
  165. package/src/generated/api/SfuEnsureMembershipParams.ts +3 -0
  166. package/src/generated/api/SfuMigrateEvent.ts +20 -0
  167. package/src/generated/api/{KeepAliveQueryRequest.ts → SfuNeighbourhoodParams.ts} +1 -1
  168. package/src/generated/api/SfuParticipantQualityPreference.ts +6 -0
  169. package/src/generated/api/{PerspectiveSubscribeQueryResult.ts → SfuPerspectiveParams.ts} +4 -1
  170. package/src/generated/api/SfuQualityPreferenceParams.ts +7 -0
  171. package/src/generated/api/SfuRoomInfo.ts +7 -0
  172. package/src/generated/api/SfuRoomParams.ts +3 -0
  173. package/src/generated/api/SfuRoomParticipantInfo.ts +8 -0
  174. package/src/generated/api/SfuRoomRoster.ts +12 -0
  175. package/src/generated/api/SfuSendDataParams.ts +7 -0
  176. package/src/generated/api/SfuSetConfigParams.ts +4 -0
  177. package/src/generated/api/SfuStatus.ts +24 -0
  178. package/src/generated/api/TrackMapEntry.ts +18 -0
  179. package/src/generated/api/UpdateSubjectRequest.ts +10 -0
  180. package/src/generated/api/index.ts +3 -0
  181. package/src/index.ts +7 -0
  182. package/src/model/Ad4mModel.test.ts +255 -231
  183. package/src/model/Ad4mModel.ts +271 -4
  184. package/src/model/ModelQueryBuilder.ts +103 -310
  185. package/src/model/abstract-classes.test.ts +225 -0
  186. package/src/model/decorators.ts +81 -0
  187. package/src/model/shacl-gen.ts +13 -0
  188. package/src/model/types.ts +7 -0
  189. package/src/neighbourhood/MeshManager.test.ts +2640 -0
  190. package/src/neighbourhood/MeshManager.ts +1350 -0
  191. package/src/neighbourhood/NeighbourhoodClient.ts +271 -0
  192. package/src/neighbourhood/NeighbourhoodProxy.test.ts +23 -0
  193. package/src/neighbourhood/NeighbourhoodProxy.ts +247 -1
  194. package/src/neighbourhood/Session.test.ts +800 -0
  195. package/src/neighbourhood/Session.ts +525 -0
  196. package/src/neighbourhood/SfuManager.test.ts +677 -0
  197. package/src/neighbourhood/SfuManager.ts +803 -0
  198. package/src/neighbourhood/SfuTypes.ts +40 -0
  199. package/src/perspectives/FlowInstance.ts +108 -31
  200. package/src/perspectives/FlowModels.ts +8 -18
  201. package/src/perspectives/LiveQuery.test.ts +197 -0
  202. package/src/perspectives/LiveQuery.ts +189 -0
  203. package/src/perspectives/PerspectiveClient.ts +51 -51
  204. package/src/perspectives/PerspectiveProxy.test.ts +85 -401
  205. package/src/perspectives/PerspectiveProxy.ts +126 -536
  206. package/src/perspectives/TextContent.test.ts +123 -0
  207. package/src/perspectives/TextContent.ts +36 -0
  208. package/src/perspectives/WakerSubscriptionManager.test.ts +88 -6
  209. package/src/perspectives/WakerSubscriptionManager.ts +69 -18
  210. package/src/shacl/SHACLFlow.ts +7 -4
  211. package/src/shacl/SHACLShape.test.ts +2 -1
  212. package/src/shacl/SHACLShape.ts +49 -0
  213. package/lib/src/generated/api/KeepAliveQueryRequest.d.ts +0 -3
  214. package/lib/src/generated/api/PerspectiveModelSubscribeResult.d.ts +0 -7
  215. package/lib/src/generated/api/PerspectiveQuerySubscriptionFilter.d.ts +0 -6
  216. package/lib/src/generated/api/PerspectiveSubscribeQueryResult.d.ts +0 -4
  217. package/src/generated/api/PerspectiveModelSubscribeResult.ts +0 -6
  218. package/src/generated/api/PerspectiveQuerySubscriptionFilter.ts +0 -3
  219. /package/lib/src/generated/api/{KeepAliveQueryRequest.js → AgentsByDidsRequest.js} +0 -0
  220. /package/lib/src/generated/api/{PerspectiveModelSubscribeResult.js → CallSessionInfo.js} +0 -0
  221. /package/lib/src/generated/api/{PerspectiveQuerySubscriptionFilter.js → DiscardBatchRequest.js} +0 -0
  222. /package/lib/src/generated/api/{PerspectiveSubscribeQueryResult.js → FlowStateChangedEvent.js} +0 -0
@@ -2,7 +2,7 @@ import { PerspectiveClient } from "./PerspectiveClient";
2
2
  import type { EventMap, ScopedEventName } from "../generated/api/Events";
3
3
  import type {
4
4
  FlowFireOutcome, FlowMintedReceipt, FlowOutputRef, FlowProposeResult,
5
- FlowReceiptVerdict, FlowValidOutput,
5
+ FlowReceiptVerdict, FlowStateEntry, FlowValidOutput,
6
6
  } from "./FlowInstance";
7
7
  import { CallOptions } from "../apiClient";
8
8
  import { Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkMutations } from "../links/Links";
@@ -18,6 +18,7 @@ import { AIClient } from "../ai/AIClient";
18
18
  import { getPropertiesMetadata, getRelationsMetadata } from "../model/decorators";
19
19
  import { getCachedResult, setCachedResult, invalidatePerspectiveCache } from "../model/query-cache";
20
20
  import { AllInstancesResult } from "../model/types";
21
+ import { LiveQuery, Subscribed } from "./LiveQuery";
21
22
  import type { TranscriptTurn } from "../generated/api";
22
23
  import type { JsonValue } from "../generated/api/serde_json/JsonValue";
23
24
 
@@ -39,431 +40,73 @@ function extractNamespaceFromUri(uri: string): string {
39
40
  return uri;
40
41
  }
41
42
 
42
- /** Proxy object for a subscribed Prolog query that provides real-time updates
43
- *
44
- * This class handles:
45
- * - Keeping the subscription alive by sending periodic keepalive signals
46
- * - Managing callbacks for result updates
47
- * - Subscribing to query updates via WebSocket subscriptions
48
- * - Maintaining the latest query result
49
- * - Ensuring subscription is fully initialized before allowing access
50
- * - Cleaning up resources when disposed
51
- *
52
- * The subscription will remain active as long as keepalive signals are sent.
53
- * Make sure to call dispose() when you're done with the subscription to clean up
54
- * resources, stop keepalive signals, and notify the backend to remove the subscription.
55
- *
56
- * The subscription goes through an initialization process where it waits for the first
57
- * result to come through the subscription channel. You can await the `initialized`
58
- * promise to ensure the subscription is ready. The initialization will timeout after
59
- * 30 seconds if no result is received.
60
- *
61
- * Example usage:
43
+
44
+ /** A live SPARQL query with its latest result.
45
+ *
46
+ * `subscribe()` opens the query and resolves once the first result is in;
47
+ * `onResult()` callbacks then get every later result. The executor sends
48
+ * only changes; `LiveQuery` applies them, recovers from a missed update and
49
+ * re-opens the query after a reconnect. Call `dispose()` when done.
50
+ *
62
51
  * ```typescript
63
- * const subscription = await perspective.subscribeInfer("my_query(X)");
64
- * // At this point the subscription is already initialized since subscribeInfer waits
65
- *
66
- * // Set up callback for future updates
67
- * const removeCallback = subscription.onResult(result => {
68
- * console.log("New result:", result);
69
- * });
70
- *
71
- * // Later: clean up subscription and notify backend
52
+ * const subscription = await perspective.subscribeQuery("SELECT ?s WHERE { ?s ?p ?o }");
53
+ * const remove = subscription.onResult(result => console.log(result));
72
54
  * subscription.dispose();
73
55
  * ```
74
56
  */
75
57
  export class QuerySubscriptionProxy {
76
- #uuid: string;
77
- #subscriptionId: string;
78
- #client: PerspectiveClient;
79
- #callbacks: Set<QueryCallback>;
80
- #keepaliveTimer: number;
81
- #unsubscribe?: () => void;
82
- #reconnectUnsub?: () => void;
83
- #latestResult: AllInstancesResult|null;
84
- #disposed: boolean = false;
58
+ #live: LiveQuery;
59
+ #callbacks = new Set<QueryCallback>();
85
60
  #initialized: Promise<boolean>;
86
61
  #initResolve?: (value: boolean) => void;
87
62
  #initReject?: (reason?: any) => void;
88
- #initTimeoutId?: NodeJS.Timeout;
89
- #query: string;
90
- // Monotonic token guarding the three concurrent writers of
91
- // `#unsubscribe`/`#subscriptionId` (full subscribe() from the keepalive
92
- // and init-timeout retry paths, and the reconnect swap handler). Each
93
- // writer bumps it on entry and re-checks after every await; a mismatch
94
- // means a newer writer took over while we were suspended, so the stale
95
- // continuation must back out instead of clobbering the newer state
96
- // (worst case otherwise: an overwritten-but-never-called unsubscribe
97
- // leaks its callback in ApiClient._wsCallbacks for the client lifetime).
98
- #generation: number = 0;
99
-
100
- /** Creates a new query subscription
101
- * @param uuid - The UUID of the perspective
102
- * @param query - The Prolog query to subscribe to
103
- * @param client - The PerspectiveClient instance to use for communication
104
- */
63
+
105
64
  constructor(uuid: string, query: string, client: PerspectiveClient) {
106
- this.#uuid = uuid;
107
- this.#query = query;
108
- this.#client = client;
109
- this.#callbacks = new Set();
110
- this.#latestResult = null;
111
-
112
- // Create the promise once and store its resolve/reject
65
+ this.#live = new LiveQuery(client, uuid, () => client.subscribeQuery(uuid, query), result => this.#deliver(result));
113
66
  this.#initialized = new Promise<boolean>((resolve, reject) => {
114
67
  this.#initResolve = resolve;
115
68
  this.#initReject = reject;
116
69
  });
70
+ // `subscribe()` throws the same error, so a caller who never reads
71
+ // `initialized` must not get an unhandled rejection from it.
72
+ this.#initialized.catch(() => {});
117
73
  }
118
74
 
75
+ /** Open the query; resolves with the first result delivered. */
119
76
  async subscribe() {
120
- // Invalidate any suspended writer (older subscribe() or reconnect
121
- // swap parked on an await) — see #generation.
122
- const generation = ++this.#generation;
123
-
124
- // Remove any prior reconnect listener FIRST — before we touch
125
- // `#unsubscribe`. Rationale: `#unsubscribe()` calls into
126
- // `ApiClient.subscribe()`'s deleter, which closes the WebSocket
127
- // whenever this query owned the last `_wsCallbacks` entry (and no
128
- // RPCs are pending). The subsequent `subscribeQuery()` below then
129
- // re-opens a fresh socket, and that fresh `onopen` fires the
130
- // reconnect callback set. If the OLD reconnect listener is still
131
- // in that set, it re-enters this method, closes the socket again,
132
- // reopens again … an endless resubscribe loop. Clearing the
133
- // listener up-front breaks the cycle; a fresh listener is
134
- // installed at the end of a successful subscribe(), and a
135
- // full-retry recovery listener in the catch block on failure.
136
- if (this.#reconnectUnsub) {
137
- this.#reconnectUnsub();
138
- this.#reconnectUnsub = undefined;
139
- }
140
-
141
- // Clean up previous subscription attempt if retrying
142
- if (this.#unsubscribe) {
143
- this.#unsubscribe();
144
- this.#unsubscribe = undefined;
145
- }
146
-
147
- // Clear any existing timeout
148
- if (this.#initTimeoutId) {
149
- clearTimeout(this.#initTimeoutId);
150
- this.#initTimeoutId = undefined;
151
- }
152
-
153
- // Clear any existing keepalive timer to prevent accumulation
154
- if (this.#keepaliveTimer) {
155
- clearTimeout(this.#keepaliveTimer);
156
- this.#keepaliveTimer = undefined;
157
- }
158
-
159
- // A retry (init timeout, failed keepalive) replaces the hold this
160
- // proxy already has; release it so the proxy never holds two.
161
- this.#releaseHold();
162
-
163
77
  try {
164
- // Initialize the query subscription
165
- let initialResult;
166
- initialResult = await this.#client.subscribeQuery(this.#uuid, this.#query);
167
-
168
- // A newer writer (another subscribe() or a reconnect swap) took
169
- // over while we awaited — back out without touching shared state,
170
- // and release the now-orphaned server-side subscription so it
171
- // doesn't linger until its keepalive TTL expires.
172
- if (this.#disposed || this.#generation !== generation) {
173
- this.#client.disposeQuerySubscription(this.#uuid, initialResult.subscriptionId)
174
- .catch(e => console.error('Error disposing superseded query subscription:', e));
175
- return;
176
- }
177
-
178
- this.#subscriptionId = initialResult.subscriptionId;
179
-
180
- // Process the initial result immediately for fast UX.
181
- // The subscribeQuery() RPC call already returns the initial result,
182
- // so treat that as successful initialization instead of waiting for a
183
- // follow-up WebSocket update that may never arrive until the query changes.
184
- if (initialResult.result !== undefined) {
185
- this.#deliverResult(initialResult.result);
186
- } else {
187
- console.warn('⚠️ No initial result returned from subscribeQuery!');
188
-
189
- // Only keep the initialization timeout when the backend did not
190
- // provide an initial result up front.
191
- this.#initTimeoutId = setTimeout(() => {
192
- console.error('Subscription initialization timed out after 30 seconds. Resubscribing...');
193
- // Recursively retry subscription, catching any errors
194
- this.subscribe().catch(error => {
195
- console.error('Error during subscription retry after timeout:', error);
196
- });
197
- }, 30000);
198
- }
199
-
200
- // Subscribe to query updates
201
- this.#unsubscribe = this.#client.subscribeToQueryUpdates(
202
- this.#subscriptionId,
203
- (updateResult) => this.#deliverResult(updateResult)
204
- );
78
+ this.#deliver(await this.#live.start());
205
79
  } catch (error) {
206
- console.error('Error setting up subscription:', error);
207
-
208
- // Reject the promise if this is the first attempt
209
- if (this.#initReject) {
210
- this.#initReject(error);
211
- this.#initResolve = undefined;
212
- this.#initReject = undefined;
213
- }
214
-
215
- // Restore reconnect recovery before rethrowing. The listener was
216
- // removed at the top of this method; without re-installing one
217
- // here, a single failed resubscribe (e.g. subscribeQuery timing
218
- // out during a network flap) would leave the proxy permanently
219
- // dead: the keepalive loop stops itself on resubscribe failure,
220
- // and nothing else retries. The recovery listener runs the FULL
221
- // subscribe() (not the swap-in-place handler) because after a
222
- // failed attempt there is no keepalive loop left to feed the new
223
- // server subscription — subscribe() restarts it. This is
224
- // loop-safe: in this failed state the proxy owns no
225
- // `_wsCallbacks` entry (the old one was unsubscribed at the top
226
- // of this method and no new one got registered), so the
227
- // subscribe() it triggers has nothing to unsubscribe → the
228
- // socket never closes/reopens under it → no re-entrant onopen.
229
- if (!this.#disposed && this.#generation === generation && this.#client.onReconnect) {
230
- this.#reconnectUnsub = this.#client.onReconnect(() => {
231
- if (this.#disposed) return;
232
- console.log('WebSocket reconnected — retrying failed subscription for query:', this.#query);
233
- this.subscribe().catch(e => {
234
- console.error('Error during subscription retry after reconnect:', e);
235
- });
236
- });
237
- }
238
-
239
- throw error; // Re-throw so caller knows it failed
240
- }
241
-
242
- // Start keepalive loop
243
- this.#startKeepalive(generation);
244
-
245
- // Register for reconnect notification — on WebSocket reconnect,
246
- // immediately re-establish a fresh server-side subscription instead
247
- // of waiting up to 30s for the keepalive to fail.
248
- //
249
- // We deliberately do NOT call `this.subscribe()` here. Full subscribe
250
- // runs `#unsubscribe` first, which delegates to `ApiClient.subscribe`'s
251
- // deleter — that closes the WebSocket when this query owned the LAST
252
- // `_wsCallbacks` entry. The subsequent `subscribeQuery` reopens the
253
- // socket, whose fresh `onopen` fires every registered reconnect
254
- // callback again → recursion (CodeRabbit's original finding). And
255
- // during that close→reopen gap, RPCs in flight from OTHER proxies
256
- // fail with `503 WebSocket not connected` (observed in
257
- // integration-tests-mcp `should fire onWake when mention uses agent DID`
258
- // after PR #899's initial fix — the WakerSubscriptionManager tests
259
- // share a wakerClient across cases, so any dying reconnect handler
260
- // interferes with sibling subscriptions).
261
- //
262
- // The correct shape is a swap-in-place: get a new server-side
263
- // subscription ID via `subscribeQuery`, register a new client-side
264
- // callback FIRST, and only then unsubscribe the old one. That way
265
- // `_wsCallbacks.size` never dips to 0 during the transition, so the
266
- // socket doesn't close, no reconnect loop, and no cross-proxy 503s.
267
- // Any prior listener was already removed at the top of this method
268
- // (see the note there for why cleanup must run before `#unsubscribe`,
269
- // not here).
270
- if (this.#client.onReconnect) {
271
- this.#reconnectUnsub = this.#client.onReconnect(async () => {
272
- if (this.#disposed) return;
273
- // The handler is a writer of `#unsubscribe`/`#subscriptionId`
274
- // too, so it takes its own generation — see #generation.
275
- const swapGeneration = ++this.#generation;
276
- console.log(
277
- 'WebSocket reconnected — re-establishing server subscription for query:',
278
- this.#query,
279
- );
280
- try {
281
- const newInitial = await this.#client.subscribeQuery(this.#uuid, this.#query);
282
- if (this.#disposed || this.#generation !== swapGeneration) {
283
- // A newer writer took over while we awaited — back out
284
- // and release the orphaned server-side subscription.
285
- this.#client.disposeQuerySubscription(this.#uuid, newInitial.subscriptionId)
286
- .catch(e => console.error('Error disposing superseded query subscription:', e));
287
- return;
288
- }
289
- const newSubId = newInitial.subscriptionId;
290
-
291
- // Register the NEW client-side callback BEFORE removing the
292
- // old one — keeps `_wsCallbacks.size >= 1` across the swap.
293
- const newUnsub = this.#client.subscribeToQueryUpdates(
294
- newSubId,
295
- (updateResult) => this.#deliverResult(updateResult),
296
- );
297
- const oldUnsub = this.#unsubscribe;
298
- this.#unsubscribe = newUnsub;
299
- this.#releaseHold();
300
- this.#subscriptionId = newSubId;
301
- if (oldUnsub) oldUnsub();
302
-
303
- // Our generation bump invalidated the running keepalive
304
- // loop — restart it under our generation so the new
305
- // server subscription keeps receiving keepalives.
306
- clearTimeout(this.#keepaliveTimer);
307
- this.#startKeepalive(swapGeneration);
308
-
309
- // Deliver the fresh initial result if the server included one
310
- // (matches the eager-delivery path in the main subscribe() body).
311
- // #deliverResult also clears a still-pending init timeout and
312
- // resolves #initialized, keeping this path symmetric with the
313
- // update callback in subscribe() — without it, a swap landing
314
- // while initialization was pending would leave the 30s init
315
- // timer armed and trigger a spurious full resubscribe.
316
- if (newInitial.result !== undefined) {
317
- this.#deliverResult(newInitial.result);
318
- }
319
- } catch (error) {
320
- console.error(
321
- 'Error re-establishing subscription after reconnect:',
322
- error,
323
- );
324
- // Our generation bump invalidated the running keepalive
325
- // loop; if nothing newer superseded us, restart it so
326
- // liveness is preserved — its keepAliveQuery against the
327
- // dead old subscription will fail and fall back to a
328
- // full subscribe(). The reconnect listener also remains
329
- // installed, so a later reconnect retries this handler.
330
- if (!this.#disposed && this.#generation === swapGeneration) {
331
- clearTimeout(this.#keepaliveTimer);
332
- this.#startKeepalive(swapGeneration);
333
- }
334
- }
335
- });
80
+ this.#initReject?.(error);
81
+ this.#initResolve = this.#initReject = undefined;
82
+ throw error;
336
83
  }
337
84
  }
338
85
 
339
- /** Get the subscription ID for this query subscription
340
- *
341
- * This is a unique identifier assigned when the subscription was created.
342
- * It can be used to reference this specific subscription, for example when
343
- * sending keepalive signals.
344
- *
345
- * @returns The subscription ID string
346
- */
86
+ /** The executor's id for this subscription. */
347
87
  get id(): string {
348
- return this.#subscriptionId;
88
+ return this.#live.id;
349
89
  }
350
90
 
351
- /** Promise that resolves when the subscription has received its first result
352
- * through the subscription channel. This ensures the subscription is fully
353
- * set up before allowing access to results or updates.
354
- *
355
- * If no result is received within 30 seconds, the subscription will automatically
356
- * retry. The promise will remain pending until a subscription message successfully
357
- * arrives, or until a fatal error occurs during subscription setup.
358
- *
359
- * Note: You typically don't need to await this directly since the subscription
360
- * creation methods (like subscribeInfer) already wait for initialization.
361
- */
91
+ /** Resolves once the first result has arrived. */
362
92
  get initialized(): Promise<boolean> {
363
93
  return this.#initialized;
364
94
  }
365
95
 
366
- /** Get the latest query result
367
- *
368
- * This returns the most recent result from the query, which could be either:
369
- * - The initial result from when the subscription was created
370
- * - The latest update received through the subscription
371
- *
372
- * @returns The latest query result as a string (usually a JSON array of bindings)
373
- */
96
+ /** The latest result. */
374
97
  get result(): AllInstancesResult {
375
- return this.#latestResult;
98
+ return this.#live.result;
376
99
  }
377
100
 
378
- /** Add a callback that will be called whenever new results arrive
379
- *
380
- * The callback will be called immediately with the current result,
381
- * and then again each time the query results change.
382
- *
383
- * @param callback - Function that takes a result string and processes it
384
- * @returns A function that can be called to remove this callback
385
- *
386
- * Example:
387
- * ```typescript
388
- * const removeCallback = subscription.onResult(result => {
389
- * const bindings = JSON.parse(result);
390
- * console.log("New bindings:", bindings);
391
- * });
392
- *
393
- * // Later: stop receiving updates
394
- * removeCallback();
395
- * ```
396
- */
101
+ /** Call `callback` with every later result. Returns a remover. */
397
102
  onResult(callback: QueryCallback): () => void {
398
103
  this.#callbacks.add(callback);
399
104
  return () => this.#callbacks.delete(callback);
400
105
  }
401
106
 
402
- /** Deliver a result to consumers: complete a still-pending
403
- * initialization (clear the 30s init timeout, resolve #initialized),
404
- * record the result as latest, and notify all callbacks. Shared by the
405
- * initial-result path, the update callback, and the reconnect swap
406
- * handler so all three stay lifecycle-symmetric. */
407
- #deliverResult(result: AllInstancesResult) {
408
- if (this.#initTimeoutId) {
409
- clearTimeout(this.#initTimeoutId);
410
- this.#initTimeoutId = undefined;
411
- }
412
- // Resolve the initialization promise (only resolves once)
413
- if (this.#initResolve) {
414
- this.#initResolve(true);
415
- this.#initResolve = undefined; // Prevent double-resolve
416
- this.#initReject = undefined;
417
- }
418
- this.#latestResult = result;
419
- this.#notifyCallbacks(result);
420
- }
421
-
422
- /** Start the keepalive loop for the given generation. The loop runs
423
- * every 30s until it is superseded (generation mismatch — a newer
424
- * subscribe() or reconnect swap took over) or the proxy is disposed.
425
- * On a keepalive error it falls back to a full subscribe(). */
426
- #startKeepalive(generation: number) {
427
- const keepaliveLoop = async () => {
428
- // Generation check kills orphaned loops: a loop whose
429
- // keepAliveQuery was in flight while a newer writer ran is not
430
- // cancelled by clearTimeout and would otherwise reschedule
431
- // itself alongside the newer loop.
432
- if (this.#disposed || this.#generation !== generation) return;
433
-
434
- try {
435
- await this.#client.keepAliveQuery(this.#uuid, this.#subscriptionId);
436
- } catch (e) {
437
- if (this.#disposed || this.#generation !== generation) return;
438
- console.error('Error in keepalive:', e);
439
- // try to reinitialize the subscription
440
- console.log('Reinitializing subscription for query:', this.#query);
441
- try {
442
- await this.subscribe();
443
- console.log('Subscription reinitialized');
444
- } catch (resubscribeError) {
445
- console.error('Error during resubscription from keepalive:', resubscribeError);
446
- // Don't schedule another keepalive on resubscribe failure.
447
- // Recovery is not lost: the failed subscribe() installed a
448
- // reconnect listener that retries the full subscribe.
449
- return;
450
- }
451
- // subscribe() succeeded and started its own keepalive loop
452
- // under a new generation — this loop is done.
453
- return;
454
- }
455
-
456
- // Schedule next keepalive if still the active generation
457
- if (!this.#disposed && this.#generation === generation) {
458
- this.#keepaliveTimer = setTimeout(keepaliveLoop, 30000) as unknown as number;
459
- }
460
- };
461
-
462
- this.#keepaliveTimer = setTimeout(keepaliveLoop, 30000) as unknown as number;
463
- }
464
-
465
- /** Internal method to notify all callbacks of a new result */
466
- #notifyCallbacks(result: AllInstancesResult) {
107
+ #deliver(result: AllInstancesResult) {
108
+ this.#initResolve?.(true);
109
+ this.#initResolve = this.#initReject = undefined;
467
110
  for (const callback of this.#callbacks) {
468
111
  try {
469
112
  callback(result);
@@ -473,55 +116,10 @@ export class QuerySubscriptionProxy {
473
116
  }
474
117
  }
475
118
 
476
- /** Clean up the subscription and stop keepalive signals
477
- *
478
- * This method:
479
- * 1. Stops the keepalive timer
480
- * 2. Unsubscribes from subscription updates
481
- * 3. Clears all registered callbacks
482
- * 4. Cleans up any pending initialization timeout
483
- *
484
- * After calling this method, the subscription is no longer active and
485
- * will not receive any more updates. The instance should be discarded.
486
- * Calling it again is a no-op: subscribers of the same query share one
487
- * executor subscription, and only the first call releases this proxy's
488
- * hold on it.
489
- */
119
+ /** End the subscription on the executor and drop all callbacks. */
490
120
  dispose() {
491
- this.#disposed = true;
492
- // Invalidate any suspended writer so a mid-flight subscribe() or
493
- // reconnect swap backs out instead of resurrecting state.
494
- this.#generation++;
495
- clearTimeout(this.#keepaliveTimer);
496
- if (this.#unsubscribe) {
497
- this.#unsubscribe();
498
- }
499
- if (this.#reconnectUnsub) {
500
- this.#reconnectUnsub();
501
- this.#reconnectUnsub = undefined;
502
- }
121
+ this.#live.dispose();
503
122
  this.#callbacks.clear();
504
- if (this.#initTimeoutId) {
505
- clearTimeout(this.#initTimeoutId);
506
- this.#initTimeoutId = undefined;
507
- }
508
-
509
- this.#releaseHold();
510
- }
511
-
512
- /** Release this proxy's hold on its executor subscription, at most once.
513
- *
514
- * The executor hands every subscriber of the same query the same
515
- * subscription id and removes the entry when the last holder releases
516
- * it. The id is cleared before the RPC, so a repeated dispose() is a
517
- * local no-op and cannot release another subscriber's hold. */
518
- #releaseHold() {
519
- const subscriptionId = this.#subscriptionId;
520
- this.#subscriptionId = undefined;
521
- if (subscriptionId) {
522
- this.#client.disposeQuerySubscription(this.#uuid, subscriptionId)
523
- .catch(e => console.error('Error disposing query subscription:', e));
524
- }
525
123
  }
526
124
  }
527
125
 
@@ -961,6 +559,49 @@ export class PerspectiveProxy {
961
559
  return await this.#client.flowValidOutputs(this.#handle.uuid, flow, state)
962
560
  }
963
561
 
562
+ /**
563
+ * The state each flow instance is in, as **this agent's** executor last
564
+ * derived it — one entry per instance it has derived, optionally narrowed
565
+ * to `instances`. An instance missing from the answer has not been
566
+ * derived here yet; it stands at its flow's first state.
567
+ *
568
+ * The state is not stored on the graph: the engine derives it from the
569
+ * signed proposals and keeps what it derived per agent, outside the
570
+ * perspective. So no other agent — a co-owner on the same node included —
571
+ * can read or write your entries, and a link query never sees them.
572
+ * `FlowInstance.findAll` / `start` call this for you.
573
+ */
574
+ async flowStates(instances?: string[]): Promise<FlowStateEntry[]> {
575
+ return await this.#client.flowStates(this.#handle.uuid, instances)
576
+ }
577
+
578
+ /**
579
+ * The proposals of `instance` whose votes settled an edge, as this
580
+ * agent's executor recorded them — the flow's history, sorted by URI.
581
+ * Replaces the `resolvedAs` property proposals used to carry.
582
+ */
583
+ async flowFired(instance: string): Promise<string[]> {
584
+ return await this.#client.flowFired(this.#handle.uuid, instance)
585
+ }
586
+
587
+ /**
588
+ * Called whenever a flow instance on this perspective changes state on
589
+ * this agent's executor, or an edge settles: `{ instance, from, to,
590
+ * firedProposals, caughtUp }`. Only this agent's sockets receive it.
591
+ *
592
+ * When the executor first derives an instance that already has history
593
+ * (it synced in, or the executor was upgraded) it is called once with
594
+ * `caughtUp: true`, `from: null` and no `firedProposals`: the settles
595
+ * before that are history, but `to` is the state to show for a run that
596
+ * read as not derived (`FlowInstance.currentStateName === undefined`).
597
+ *
598
+ * Returns a function that removes the handler; {@link dispose} removes
599
+ * it too.
600
+ */
601
+ onFlowStateChanged(handler: (event: EventMap["flow-state-changed"]) => void): () => void {
602
+ return this.on("flow-state-changed", handler)
603
+ }
604
+
964
605
  /** Mint and store the receipt for a completed flow run. */
965
606
  async mintFlowReceipt(instanceUri: string): Promise<FlowMintedReceipt> {
966
607
  return await this.#client.mintFlowReceipt(this.#handle.uuid, instanceUri)
@@ -1030,11 +671,13 @@ export class PerspectiveProxy {
1030
671
  * triples (written by `addSdna`). Callers no longer ship shape
1031
672
  * metadata with the query; the perspective is the source of truth.
1032
673
  *
1033
- * @param className - The model class name (e.g. "Recipe")
674
+ * @param className - The model class name (e.g. "Recipe"), or several: one
675
+ * query over their union, whose rows carry `__subjectClass` and
676
+ * `__subjectClasses` (#1238)
1034
677
  * @param queryJson - Structured query as JSON string
1035
678
  * @returns Object with `instances` array and `totalCount`
1036
679
  */
1037
- async modelQuery(className: string, queryJson: string, options?: CallOptions): Promise<{ instances: any[], totalCount: number }> {
680
+ async modelQuery(className: string | string[], queryJson: string, options?: CallOptions): Promise<{ instances: any[], totalCount: number }> {
1038
681
  return await this.#client.modelQuery(this.#handle.uuid, className, queryJson, options);
1039
682
  }
1040
683
 
@@ -1096,18 +739,16 @@ export class PerspectiveProxy {
1096
739
  }
1097
740
 
1098
741
  /**
1099
- * Subscribe to model query changes. Builds trigger SPARQL from the model shape
1100
- * internally in Rust, registers a subscription, runs the initial query, and
1101
- * pushes updated results when relevant links change.
1102
- *
1103
- * The subscription reuses the same WS-RPC subscription channel as subscribeQuery().
1104
- * Use keepAliveQuery() / disposeQuerySubscription() with the returned subscriptionId.
742
+ * Open a live model query on the executor. Later changes arrive as
743
+ * updates; `LiveQuery` (or `ModelQueryBuilder.subscribe()`) applies them.
744
+ * The subscription ends with `disposeQuerySubscription()` or when the
745
+ * socket closes.
1105
746
  *
1106
- * @param className - The model class name
747
+ * @param className - The model class name, or several (same as modelQuery)
1107
748
  * @param queryJson - JSON-serialized query parameters (same as modelQuery)
1108
- * @returns Object with `subscriptionId` and initial `result`
749
+ * @returns `subscriptionId`, initial `result` and `revision` (0)
1109
750
  */
1110
- async modelSubscribe(className: string, queryJson: string): Promise<{ subscriptionId: string, result: any }> {
751
+ async modelSubscribe(className: string | string[], queryJson: string): Promise<Subscribed> {
1111
752
  return await this.#client.modelSubscribe(this.#handle.uuid, className, queryJson);
1112
753
  }
1113
754
 
@@ -1565,6 +1206,8 @@ export class PerspectiveProxy {
1565
1206
  async ensureSubjectClasses(jsClasses: any[]): Promise<void> {
1566
1207
  const entries: { name: string; sdnaCode?: string; sdnaType: "subject_class" | "flow" | "custom"; shaclJson?: string }[] = [];
1567
1208
  for (const jsClass of jsClasses) {
1209
+ // Built-in classes (`TextContent`) live in the executor, not here.
1210
+ if (Object.prototype.hasOwnProperty.call(jsClass, 'builtinUri')) continue;
1568
1211
  const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
1569
1212
  if (this.#ensuredSubjectClasses.has(className)) continue;
1570
1213
 
@@ -1933,6 +1576,14 @@ export class PerspectiveProxy {
1933
1576
  return exprAddr as unknown as B extends undefined ? T : string;
1934
1577
  }
1935
1578
 
1579
+ /** Sets properties of an existing instance in the executor. Through an
1580
+ * abstract class (#1435), each value is written by every class of the
1581
+ * record that the abstract class reads, under its own name. */
1582
+ async updateSubject(className: string, exprAddr: string, values: Record<string, any>, batchId?: string) {
1583
+ await this.#client.updateSubject(this.#handle.uuid, className, exprAddr, JSON.stringify(values), batchId);
1584
+ invalidatePerspectiveCache(this.#handle.uuid);
1585
+ }
1586
+
1936
1587
  async getSubjectData<T>(subjectClass: T, exprAddr: string): Promise<T> {
1937
1588
  if (typeof subjectClass === "string") {
1938
1589
  return JSON.parse(await this.#client.getSubjectData(this.#handle.uuid, JSON.stringify({className: subjectClass}), exprAddr))
@@ -1990,8 +1641,26 @@ export class PerspectiveProxy {
1990
1641
  * and won't be executed until the batch is committed.
1991
1642
  */
1992
1643
  async removeSubject<T>(subjectClass: T, exprAddr: string, batchId?: string) {
1644
+ // A built-in abstract class (`TextContent`, #1446) is never stored,
1645
+ // so it has no marker: the executor dispatches it by its URI.
1646
+ const ctor = (subjectClass as any)?.constructor;
1647
+ if (typeof subjectClass === "object" && ctor && Object.prototype.hasOwnProperty.call(ctor, 'builtinUri')) {
1648
+ await this.#client.removeSubject(this.#handle.uuid, ctor.builtinUri, exprAddr, batchId);
1649
+ invalidatePerspectiveCache(this.#handle.uuid);
1650
+ return;
1651
+ }
1993
1652
  let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass)
1994
1653
 
1654
+ // An abstract class (#1435) is never a record's class: the executor
1655
+ // runs the destructors of the record's classes it reads.
1656
+ const shapePattern = new RegExp(`[/:#]${this.escapeRegExp(className)}Shape$`);
1657
+ const markers = await this.get(new LinkQuery({ predicate: "ad4m://abstract" }));
1658
+ if (markers.some((link) => shapePattern.test(link.data.source))) {
1659
+ await this.#client.removeSubject(this.#handle.uuid, className, exprAddr, batchId);
1660
+ invalidatePerspectiveCache(this.#handle.uuid);
1661
+ return;
1662
+ }
1663
+
1995
1664
  // Get destructor actions from SHACL links (Prolog-free)
1996
1665
  let actions = await this.getActionsFromSHACL(className, "ad4m://destructor");
1997
1666
 
@@ -2341,6 +2010,9 @@ export class PerspectiveProxy {
2341
2010
 
2342
2011
  /** Takes a JS class (its constructor) and ensures the SHACL subject class exists. */
2343
2012
  async ensureSubjectClass(jsClass: any): Promise<void> {
2013
+ // Built-in classes (`TextContent`) live in the executor, not here.
2014
+ if (Object.prototype.hasOwnProperty.call(jsClass, 'builtinUri')) return;
2015
+
2344
2016
  // Get the class name from the JS class
2345
2017
  const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
2346
2018
 
@@ -2595,95 +2267,13 @@ export class PerspectiveProxy {
2595
2267
  return this.#client.aiClient
2596
2268
  }
2597
2269
 
2598
- /**
2599
- * Creates a subscription for a Prolog query that updates in real-time.
2600
- *
2601
- * This method:
2602
- * 1. Creates the subscription on the Rust side
2603
- * 2. Sets up the subscription callback
2604
- * 3. Waits for the initial result to come through the subscription channel
2605
- * 4. Returns a fully initialized QuerySubscriptionProxy
2606
- *
2607
- * The returned subscription is guaranteed to be ready to receive updates,
2608
- * as this method waits for the initialization process to complete.
2609
- *
2610
- * The subscription will be automatically cleaned up on both frontend and backend
2611
- * when dispose() is called. Make sure to call dispose() when you're done to
2612
- * prevent memory leaks and ensure proper cleanup of resources.
2613
- *
2614
- * @param query - Prolog query string
2615
- * @returns Initialized QuerySubscriptionProxy instance
2616
- *
2617
- * @example
2618
- * ```typescript
2619
- * // Subscribe to active todos
2620
- * const subscription = await perspective.subscribeInfer(`
2621
- * instance(Todo, "Todo"),
2622
- * property_getter("Todo", Todo, "state", "active")
2623
- * `);
2624
- *
2625
- * // Subscription is already initialized here
2626
- * console.log("Initial result:", subscription.result);
2627
- *
2628
- * // Set up callback for future updates
2629
- * subscription.onResult((todos) => {
2630
- * console.log("Active todos:", todos);
2631
- * });
2632
- *
2633
- * // Clean up subscription when done
2634
- * subscription.dispose();
2635
- * ```
2636
- */
2637
- async subscribeInfer(query: string): Promise<QuerySubscriptionProxy> {
2638
- const subscriptionProxy = new QuerySubscriptionProxy(
2639
- this.uuid,
2640
- query,
2641
- this.#client
2642
- );
2643
-
2644
- // Start the subscription on the Rust side first to get the real subscription ID
2645
- await subscriptionProxy.subscribe();
2646
-
2647
- // Wait for the initial result
2648
- await subscriptionProxy.initialized;
2649
-
2650
- return subscriptionProxy;
2651
- }
2652
-
2653
- /**
2654
- * Creates a subscription for a SPARQL query that updates in real-time.
2655
- *
2656
- * This method:
2657
- * 1. Creates the subscription on the Rust side
2658
- * 2. Sets up the subscription callback
2659
- * 3. Waits for the initial result to come through the subscription channel
2660
- * 4. Returns a fully initialized QuerySubscriptionProxy
2661
- *
2662
- * The returned subscription is guaranteed to be ready to receive updates,
2663
- * as this method waits for the initialization process to complete.
2664
- *
2665
- * The subscription will be automatically cleaned up on both frontend and backend
2666
- * when dispose() is called. Make sure to call dispose() when you're done to
2667
- * prevent memory leaks and ensure proper cleanup of resources.
2668
- *
2669
- /** Subscribe to a query with live updates via the SPARQL subscription endpoint.
2670
- * @param query - Query string
2671
- * @returns Initialized QuerySubscriptionProxy instance
2672
- */
2270
+ /** Live SPARQL query: resolves once the first result is in.
2271
+ * Call `dispose()` on the returned proxy when done. The executor
2272
+ * refuses a Prolog query (400): Prolog live queries are not supported. */
2673
2273
  async subscribeQuery(query: string): Promise<QuerySubscriptionProxy> {
2674
- const subscriptionProxy = new QuerySubscriptionProxy(
2675
- this.uuid,
2676
- query,
2677
- this.#client
2678
- );
2679
-
2680
- // Start the subscription on the Rust side first to get the real subscription ID
2681
- await subscriptionProxy.subscribe();
2682
-
2683
- // Wait for the initial result
2684
- await subscriptionProxy.initialized;
2685
-
2686
- return subscriptionProxy;
2274
+ const subscription = new QuerySubscriptionProxy(this.uuid, query, this.#client);
2275
+ await subscription.subscribe();
2276
+ return subscription;
2687
2277
  }
2688
2278
 
2689
2279
  }