@coasys/ad4m 0.13.0-test-interpretation-2 → 0.13.0-test-model-layer

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 (254) hide show
  1. package/lib/index.cjs +1982 -498
  2. package/lib/index.js +1982 -499
  3. package/lib/src/ai/AIClient.js +6 -3
  4. package/lib/src/apiClient.d.ts +40 -4
  5. package/lib/src/apiClient.js +149 -9
  6. package/lib/src/index.d.ts +3 -1
  7. package/lib/src/index.js +2 -0
  8. package/lib/src/model/Ad4mModel.d.ts +6 -5
  9. package/lib/src/model/Ad4mModel.js +246 -29
  10. package/lib/src/model/Ad4mModel.test.js +480 -735
  11. package/lib/src/model/decorators.d.ts +147 -4
  12. package/lib/src/model/decorators.js +70 -24
  13. package/lib/src/model/model-manifest.d.ts +41 -0
  14. package/lib/src/model/model-manifest.js +11 -0
  15. package/lib/src/model/query-sparql.test.js +92 -10
  16. package/lib/src/model/shacl-gen.js +33 -0
  17. package/lib/src/model/types.d.ts +9 -0
  18. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +33 -33
  19. package/lib/src/perspectives/AutoProcessor.d.ts +90 -24
  20. package/lib/src/perspectives/FlowInstance.d.ts +187 -0
  21. package/lib/src/perspectives/FlowInstance.js +336 -0
  22. package/lib/src/perspectives/FlowModels.d.ts +94 -0
  23. package/lib/src/perspectives/FlowModels.js +182 -0
  24. package/lib/src/perspectives/InterpretationModels.d.ts +12 -22
  25. package/lib/src/perspectives/InterpretationModels.js +2 -6
  26. package/lib/src/perspectives/PerspectiveClient.d.ts +68 -7
  27. package/lib/src/perspectives/PerspectiveClient.js +105 -10
  28. package/lib/src/perspectives/PerspectiveProxy.d.ts +142 -57
  29. package/lib/src/perspectives/PerspectiveProxy.js +388 -274
  30. package/lib/src/shacl/SHACLFlow.d.ts +273 -47
  31. package/lib/src/shacl/SHACLFlow.js +397 -88
  32. package/lib/src/shacl/SHACLShape.d.ts +8 -0
  33. package/lib/src/shacl/SHACLShape.js +17 -0
  34. package/lib/src/shacl/SHACLShape.test.js +82 -0
  35. package/package.json +2 -2
  36. package/src/ai/AIClient.ts +6 -3
  37. package/src/apiClient.test.ts +227 -0
  38. package/src/apiClient.ts +185 -9
  39. package/src/index.ts +3 -1
  40. package/src/model/Ad4mModel.test.ts +645 -0
  41. package/src/model/Ad4mModel.ts +245 -26
  42. package/src/model/decorators.ts +216 -35
  43. package/src/model/relation-filtering.test.ts +70 -20
  44. package/src/model/shacl-gen.ts +36 -0
  45. package/src/model/shacl-roundtrip.test.ts +130 -0
  46. package/src/model/types.ts +7 -0
  47. package/src/perspectives/AutoProcessor.ts +94 -24
  48. package/src/perspectives/FlowInstance.ts +369 -0
  49. package/src/perspectives/FlowModels.ts +157 -0
  50. package/src/perspectives/InterpretationModels.ts +13 -25
  51. package/src/perspectives/PerspectiveClient.test.ts +67 -6
  52. package/src/perspectives/PerspectiveClient.ts +142 -12
  53. package/src/perspectives/PerspectiveProxy.test.ts +406 -0
  54. package/src/perspectives/PerspectiveProxy.ts +459 -289
  55. package/src/perspectives/shacl-rpc.test.ts +258 -0
  56. package/src/shacl/SHACLFlow.test.ts +762 -35
  57. package/src/shacl/SHACLFlow.ts +680 -112
  58. package/src/shacl/SHACLShape.ts +31 -0
  59. package/lib/src/generated/rest/AIModelLoadingStatus.d.ts +0 -7
  60. package/lib/src/generated/rest/AIModelLoadingStatus.js +0 -2
  61. package/lib/src/generated/rest/AddAgentInfosRequest.d.ts +0 -3
  62. package/lib/src/generated/rest/AddAgentInfosRequest.js +0 -2
  63. package/lib/src/generated/rest/AddLinkExpressionRequest.d.ts +0 -6
  64. package/lib/src/generated/rest/AddLinkExpressionRequest.js +0 -1
  65. package/lib/src/generated/rest/AddLinkRequest.d.ts +0 -6
  66. package/lib/src/generated/rest/AddLinkRequest.js +0 -1
  67. package/lib/src/generated/rest/AddLinksBulkRequest.d.ts +0 -6
  68. package/lib/src/generated/rest/AddLinksBulkRequest.js +0 -1
  69. package/lib/src/generated/rest/AddSdnaRequest.d.ts +0 -6
  70. package/lib/src/generated/rest/AddSdnaRequest.js +0 -2
  71. package/lib/src/generated/rest/ApplyTemplateRequest.d.ts +0 -4
  72. package/lib/src/generated/rest/ApplyTemplateRequest.js +0 -2
  73. package/lib/src/generated/rest/AuthInfoInput.d.ts +0 -10
  74. package/lib/src/generated/rest/AuthInfoInput.js +0 -1
  75. package/lib/src/generated/rest/BroadcastRequest.d.ts +0 -6
  76. package/lib/src/generated/rest/BroadcastRequest.js +0 -1
  77. package/lib/src/generated/rest/CapabilityInput.d.ts +0 -5
  78. package/lib/src/generated/rest/CapabilityInput.js +0 -1
  79. package/lib/src/generated/rest/CommitBatchRequest.d.ts +0 -3
  80. package/lib/src/generated/rest/CommitBatchRequest.js +0 -2
  81. package/lib/src/generated/rest/ComputeLogEntry.d.ts +0 -9
  82. package/lib/src/generated/rest/ComputeLogEntry.js +0 -2
  83. package/lib/src/generated/rest/CreateExpressionRequest.d.ts +0 -4
  84. package/lib/src/generated/rest/CreateExpressionRequest.js +0 -2
  85. package/lib/src/generated/rest/CreatePerspectiveRequest.d.ts +0 -3
  86. package/lib/src/generated/rest/CreatePerspectiveRequest.js +0 -2
  87. package/lib/src/generated/rest/CreateSubjectRequest.d.ts +0 -6
  88. package/lib/src/generated/rest/CreateSubjectRequest.js +0 -2
  89. package/lib/src/generated/rest/CreateUserRequest.d.ts +0 -4
  90. package/lib/src/generated/rest/CreateUserRequest.js +0 -2
  91. package/lib/src/generated/rest/CreateUserResponse.d.ts +0 -5
  92. package/lib/src/generated/rest/CreateUserResponse.js +0 -2
  93. package/lib/src/generated/rest/DecoratedExpressionProof.d.ts +0 -6
  94. package/lib/src/generated/rest/DecoratedExpressionProof.js +0 -2
  95. package/lib/src/generated/rest/DecoratedLinkExpression.d.ts +0 -10
  96. package/lib/src/generated/rest/DecoratedLinkExpression.js +0 -1
  97. package/lib/src/generated/rest/DisposeQueryRequest.d.ts +0 -3
  98. package/lib/src/generated/rest/DisposeQueryRequest.js +0 -2
  99. package/lib/src/generated/rest/EmailTestRequest.d.ts +0 -6
  100. package/lib/src/generated/rest/EmailTestRequest.js +0 -2
  101. package/lib/src/generated/rest/EmbedRequest.d.ts +0 -4
  102. package/lib/src/generated/rest/EmbedRequest.js +0 -2
  103. package/lib/src/generated/rest/EntanglementProofInput.d.ts +0 -6
  104. package/lib/src/generated/rest/EntanglementProofInput.js +0 -2
  105. package/lib/src/generated/rest/EntanglementProofPreflightRequest.d.ts +0 -4
  106. package/lib/src/generated/rest/EntanglementProofPreflightRequest.js +0 -2
  107. package/lib/src/generated/rest/ExecuteCommandsRequest.d.ts +0 -4
  108. package/lib/src/generated/rest/ExecuteCommandsRequest.js +0 -2
  109. package/lib/src/generated/rest/ExportRequest.d.ts +0 -5
  110. package/lib/src/generated/rest/ExportRequest.js +0 -2
  111. package/lib/src/generated/rest/ExpressionManyRequest.d.ts +0 -3
  112. package/lib/src/generated/rest/ExpressionManyRequest.js +0 -2
  113. package/lib/src/generated/rest/ExpressionProof.d.ts +0 -4
  114. package/lib/src/generated/rest/ExpressionProof.js +0 -2
  115. package/lib/src/generated/rest/ExpressionProofInput.d.ts +0 -6
  116. package/lib/src/generated/rest/ExpressionProofInput.js +0 -2
  117. package/lib/src/generated/rest/FriendSendMessageRequest.d.ts +0 -3
  118. package/lib/src/generated/rest/FriendSendMessageRequest.js +0 -2
  119. package/lib/src/generated/rest/FriendsListRequest.d.ts +0 -3
  120. package/lib/src/generated/rest/FriendsListRequest.js +0 -2
  121. package/lib/src/generated/rest/GenerateAgentRequest.d.ts +0 -3
  122. package/lib/src/generated/rest/GenerateAgentRequest.js +0 -2
  123. package/lib/src/generated/rest/GenerateJwtRequest.d.ts +0 -4
  124. package/lib/src/generated/rest/GenerateJwtRequest.js +0 -2
  125. package/lib/src/generated/rest/GetSubjectDataRequest.d.ts +0 -4
  126. package/lib/src/generated/rest/GetSubjectDataRequest.js +0 -2
  127. package/lib/src/generated/rest/HostingInfoResponse.d.ts +0 -5
  128. package/lib/src/generated/rest/HostingInfoResponse.js +0 -2
  129. package/lib/src/generated/rest/HostingWalletResponse.d.ts +0 -4
  130. package/lib/src/generated/rest/HostingWalletResponse.js +0 -2
  131. package/lib/src/generated/rest/ImportAgentRequest.d.ts +0 -6
  132. package/lib/src/generated/rest/ImportAgentRequest.js +0 -2
  133. package/lib/src/generated/rest/ImportRequest.d.ts +0 -4
  134. package/lib/src/generated/rest/ImportRequest.js +0 -2
  135. package/lib/src/generated/rest/JoinNeighbourhoodRequest.d.ts +0 -3
  136. package/lib/src/generated/rest/JoinNeighbourhoodRequest.js +0 -2
  137. package/lib/src/generated/rest/KeepAliveQueryRequest.d.ts +0 -3
  138. package/lib/src/generated/rest/KeepAliveQueryRequest.js +0 -2
  139. package/lib/src/generated/rest/LanguageMetaInput.d.ts +0 -6
  140. package/lib/src/generated/rest/LanguageMetaInput.js +0 -2
  141. package/lib/src/generated/rest/Link.d.ts +0 -5
  142. package/lib/src/generated/rest/Link.js +0 -2
  143. package/lib/src/generated/rest/LinkExpression.d.ts +0 -10
  144. package/lib/src/generated/rest/LinkExpression.js +0 -1
  145. package/lib/src/generated/rest/LinkExpressionInput.d.ts +0 -10
  146. package/lib/src/generated/rest/LinkExpressionInput.js +0 -1
  147. package/lib/src/generated/rest/LinkInput.d.ts +0 -5
  148. package/lib/src/generated/rest/LinkInput.js +0 -2
  149. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.d.ts +0 -3
  150. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.js +0 -2
  151. package/lib/src/generated/rest/LinkMutationRequest.d.ts +0 -12
  152. package/lib/src/generated/rest/LinkMutationRequest.js +0 -1
  153. package/lib/src/generated/rest/LinkMutationResponse.d.ts +0 -9
  154. package/lib/src/generated/rest/LinkMutationResponse.js +0 -1
  155. package/lib/src/generated/rest/LinkMutations.d.ts +0 -6
  156. package/lib/src/generated/rest/LinkMutations.js +0 -1
  157. package/lib/src/generated/rest/LinkMutationsRequest.d.ts +0 -5
  158. package/lib/src/generated/rest/LinkMutationsRequest.js +0 -1
  159. package/lib/src/generated/rest/LinkStatus.d.ts +0 -1
  160. package/lib/src/generated/rest/LinkStatus.js +0 -2
  161. package/lib/src/generated/rest/LinkUpdateInput.d.ts +0 -5
  162. package/lib/src/generated/rest/LinkUpdateInput.js +0 -1
  163. package/lib/src/generated/rest/LockAgentRequest.d.ts +0 -3
  164. package/lib/src/generated/rest/LockAgentRequest.js +0 -2
  165. package/lib/src/generated/rest/LoginUserRequest.d.ts +0 -5
  166. package/lib/src/generated/rest/LoginUserRequest.js +0 -2
  167. package/lib/src/generated/rest/ModelType.d.ts +0 -1
  168. package/lib/src/generated/rest/ModelType.js +0 -2
  169. package/lib/src/generated/rest/NotificationGrantRequest.d.ts +0 -3
  170. package/lib/src/generated/rest/NotificationGrantRequest.js +0 -2
  171. package/lib/src/generated/rest/NotificationInput.d.ts +0 -10
  172. package/lib/src/generated/rest/NotificationInput.js +0 -2
  173. package/lib/src/generated/rest/OpenLinkRequest.d.ts +0 -3
  174. package/lib/src/generated/rest/OpenLinkRequest.js +0 -2
  175. package/lib/src/generated/rest/PermitCapabilityRequest.d.ts +0 -3
  176. package/lib/src/generated/rest/PermitCapabilityRequest.js +0 -2
  177. package/lib/src/generated/rest/PerspectiveInput.d.ts +0 -4
  178. package/lib/src/generated/rest/PerspectiveInput.js +0 -1
  179. package/lib/src/generated/rest/PromptRequest.d.ts +0 -4
  180. package/lib/src/generated/rest/PromptRequest.js +0 -2
  181. package/lib/src/generated/rest/PublicPerspectiveInput.d.ts +0 -4
  182. package/lib/src/generated/rest/PublicPerspectiveInput.js +0 -1
  183. package/lib/src/generated/rest/PublishLanguageRequest.d.ts +0 -5
  184. package/lib/src/generated/rest/PublishLanguageRequest.js +0 -1
  185. package/lib/src/generated/rest/PublishNeighbourhoodRequest.d.ts +0 -6
  186. package/lib/src/generated/rest/PublishNeighbourhoodRequest.js +0 -1
  187. package/lib/src/generated/rest/QueryRequest.d.ts +0 -7
  188. package/lib/src/generated/rest/QueryRequest.js +0 -2
  189. package/lib/src/generated/rest/RemoveLinkRequest.d.ts +0 -5
  190. package/lib/src/generated/rest/RemoveLinkRequest.js +0 -1
  191. package/lib/src/generated/rest/RemoveLinksBulkRequest.d.ts +0 -5
  192. package/lib/src/generated/rest/RemoveLinksBulkRequest.js +0 -1
  193. package/lib/src/generated/rest/RequestCapabilityRequest.d.ts +0 -4
  194. package/lib/src/generated/rest/RequestCapabilityRequest.js +0 -1
  195. package/lib/src/generated/rest/RequestPaymentRequest.d.ts +0 -3
  196. package/lib/src/generated/rest/RequestPaymentRequest.js +0 -2
  197. package/lib/src/generated/rest/RequestVerificationRequest.d.ts +0 -4
  198. package/lib/src/generated/rest/RequestVerificationRequest.js +0 -2
  199. package/lib/src/generated/rest/ResourceInput.d.ts +0 -4
  200. package/lib/src/generated/rest/ResourceInput.js +0 -2
  201. package/lib/src/generated/rest/SetDefaultModelRequest.d.ts +0 -4
  202. package/lib/src/generated/rest/SetDefaultModelRequest.js +0 -1
  203. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.d.ts +0 -3
  204. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.js +0 -2
  205. package/lib/src/generated/rest/SetHotWalletAddressRequest.d.ts +0 -3
  206. package/lib/src/generated/rest/SetHotWalletAddressRequest.js +0 -2
  207. package/lib/src/generated/rest/SetMultiUserRequest.d.ts +0 -3
  208. package/lib/src/generated/rest/SetMultiUserRequest.js +0 -2
  209. package/lib/src/generated/rest/SetOnlineStatusRequest.d.ts +0 -5
  210. package/lib/src/generated/rest/SetOnlineStatusRequest.js +0 -1
  211. package/lib/src/generated/rest/SetStatusRequest.d.ts +0 -3
  212. package/lib/src/generated/rest/SetStatusRequest.js +0 -2
  213. package/lib/src/generated/rest/SetUserFreeAccessRequest.d.ts +0 -4
  214. package/lib/src/generated/rest/SetUserFreeAccessRequest.js +0 -2
  215. package/lib/src/generated/rest/SignMessageRequest.d.ts +0 -3
  216. package/lib/src/generated/rest/SignMessageRequest.js +0 -2
  217. package/lib/src/generated/rest/SignalRequest.d.ts +0 -6
  218. package/lib/src/generated/rest/SignalRequest.js +0 -1
  219. package/lib/src/generated/rest/SubscribeQueryRequest.d.ts +0 -3
  220. package/lib/src/generated/rest/SubscribeQueryRequest.js +0 -2
  221. package/lib/src/generated/rest/SubscribeQueryResponse.d.ts +0 -4
  222. package/lib/src/generated/rest/SubscribeQueryResponse.js +0 -2
  223. package/lib/src/generated/rest/TrustedAgentsRequest.d.ts +0 -3
  224. package/lib/src/generated/rest/TrustedAgentsRequest.js +0 -2
  225. package/lib/src/generated/rest/UnlockAgentRequest.d.ts +0 -4
  226. package/lib/src/generated/rest/UnlockAgentRequest.js +0 -2
  227. package/lib/src/generated/rest/UpdateLinkRequest.d.ts +0 -7
  228. package/lib/src/generated/rest/UpdateLinkRequest.js +0 -1
  229. package/lib/src/generated/rest/UpdatePerspectiveRequest.d.ts +0 -3
  230. package/lib/src/generated/rest/UpdatePerspectiveRequest.js +0 -2
  231. package/lib/src/generated/rest/UpdateProfileRequest.d.ts +0 -5
  232. package/lib/src/generated/rest/UpdateProfileRequest.js +0 -1
  233. package/lib/src/generated/rest/UserStatistics.d.ts +0 -9
  234. package/lib/src/generated/rest/UserStatistics.js +0 -2
  235. package/lib/src/generated/rest/VerificationRequestResult.d.ts +0 -6
  236. package/lib/src/generated/rest/VerificationRequestResult.js +0 -2
  237. package/lib/src/generated/rest/VerifyEmailRequest.d.ts +0 -6
  238. package/lib/src/generated/rest/VerifyEmailRequest.js +0 -2
  239. package/lib/src/generated/rest/VerifySignatureRequest.d.ts +0 -5
  240. package/lib/src/generated/rest/VerifySignatureRequest.js +0 -2
  241. package/lib/src/generated/rest/WriteSettingsRequest.d.ts +0 -3
  242. package/lib/src/generated/rest/WriteSettingsRequest.js +0 -2
  243. package/lib/src/generated/rest/index.d.ts +0 -73
  244. package/lib/src/generated/rest/index.js +0 -8
  245. package/lib/src/generated/rest/routes.d.ts +0 -587
  246. package/lib/src/generated/rest/routes.js +0 -3
  247. package/lib/src/model/query-surreal.d.ts +0 -44
  248. package/lib/src/model/query-surreal.js +0 -249
  249. package/lib/src/model/surreal-utils.d.ts +0 -42
  250. package/lib/src/model/surreal-utils.js +0 -128
  251. package/lib/src/perspectives/PerspectiveProxy.test.d.ts +0 -1
  252. package/lib/src/perspectives/PerspectiveProxy.test.js +0 -34
  253. package/lib/src/restClient.d.ts +0 -52
  254. package/lib/src/restClient.js +0 -227
@@ -77,9 +77,12 @@ export class AIClient {
77
77
  async embed(modelId, text) {
78
78
  const aiEmbed = await __classPrivateFieldGet(this, _AIClient_apiClient, "f").call('ai.embed', { modelId, text });
79
79
  const compressed = base64js.toByteArray(aiEmbed);
80
- // Decode to a string via TextDecoder rather than pako's `{ to: 'string' }`
81
- // option: newer @types/pako dropped that overload, which broke the build.
82
- const decompressed = JSON.parse(new TextDecoder().decode(pako.inflate(compressed)));
80
+ // NB: pako v1 accepts `{ to: 'string' }`, pako v2 wants `{ toText: true }`,
81
+ // pako v3 also drops that overload from its bundled types. Call the
82
+ // version-agnostic form (returns Uint8Array) and decode explicitly so
83
+ // this works regardless of which pako major the lockfile pins.
84
+ const inflated = pako.inflate(compressed);
85
+ const decompressed = JSON.parse(new TextDecoder('utf-8').decode(inflated));
83
86
  return decompressed;
84
87
  }
85
88
  async openTranscriptionStream(modelId, streamCallback, params) {
@@ -11,6 +11,29 @@ export declare class RpcError extends Error {
11
11
  readonly body: string;
12
12
  constructor(status: number, body: string);
13
13
  }
14
+ /** Options accepted by [`ApiClient.call`]. */
15
+ export interface CallOptions {
16
+ /**
17
+ * AbortSignal that, when fired, sends a `request.cancel` to the
18
+ * executor and rejects the call with a DOMException (`name === 'AbortError'`).
19
+ *
20
+ * Use this for long-running operations like `querySparql` so a UI
21
+ * teardown or a newer query supersession can stop the in-flight one
22
+ * without paying the network + deserialise tax on its result.
23
+ *
24
+ * Cancellation is best-effort on the executor: the SPARQL evaluation
25
+ * itself isn't preempted (Oxigraph can't be interrupted), but the
26
+ * reply is discarded and the network traffic + JSON parsing on the
27
+ * client are skipped.
28
+ */
29
+ signal?: AbortSignal;
30
+ /**
31
+ * Per-call timeout override in ms. Defaults to [[DEFAULT_TIMEOUT_MS]].
32
+ * Use for long-running calls (LLM prompts, holochain ops) that
33
+ * legitimately exceed the default.
34
+ */
35
+ timeoutMs?: number;
36
+ }
14
37
  export declare class ApiClient {
15
38
  private baseUrl;
16
39
  private token?;
@@ -24,6 +47,8 @@ export declare class ApiClient {
24
47
  setToken(token: string): void;
25
48
  private _ws;
26
49
  private _wsCallbacks;
50
+ private _reconnectCallbacks;
51
+ private _hasConnectedOnce;
27
52
  private _pendingCalls;
28
53
  private _wsReady;
29
54
  private _wsReadyResolve;
@@ -31,6 +56,7 @@ export declare class ApiClient {
31
56
  private _wsReconnectDelay;
32
57
  private _wsClosed;
33
58
  private _wsPingTimer;
59
+ private _ignoredResponseIds;
34
60
  private _getWsUrl;
35
61
  private _ensureWs;
36
62
  private _startPing;
@@ -38,22 +64,32 @@ export declare class ApiClient {
38
64
  private _scheduleReconnect;
39
65
  /** Ensure WS is connected and ready. Lazy — connects on first use. */
40
66
  private _ready;
67
+ /**
68
+ * Like `_ready()`, but races the connection against an AbortSignal so
69
+ * that callers don't hang if the signal fires while connecting.
70
+ */
71
+ private _readyOrAbort;
41
72
  /**
42
73
  * Send an RPC call over the WebSocket connection.
43
74
  * @param type - The operation type (e.g. 'agent.get', 'perspective.all')
44
75
  * @param params - Optional parameters to include in the message
45
- * @param timeoutMs - Optional per-call timeout override in ms. Defaults to
46
- * [[DEFAULT_TIMEOUT_MS]]. Use for long-running calls (LLM prompts,
47
- * holochain ops) that legitimately exceed the default.
76
+ * @param options - Optional call options: `signal` (AbortSignal for
77
+ * cancellation) and/or `timeoutMs` (per-call timeout override,
78
+ * defaults to [[DEFAULT_TIMEOUT_MS]] — use for long-running calls
79
+ * like LLM prompts or holochain ops that legitimately exceed it).
48
80
  * @returns Promise that resolves with the result from the server
49
81
  */
50
- call<T>(type: string, params?: Record<string, unknown>, timeoutMs?: number): Promise<T>;
82
+ call<T>(type: string, params?: Record<string, unknown>, options?: CallOptions): Promise<T>;
51
83
  subscribe<T = WsEvent>(callback: (data: T) => void): () => void;
52
84
  /** Wait until the WebSocket connection is established. */
53
85
  waitForSubscription(): Promise<void>;
54
86
  /** Explicitly connect the WebSocket (optional — connection is lazy). */
55
87
  connect(): void;
56
88
  private _closeWs;
89
+ /** Register a callback that fires after a successful WebSocket reconnect.
90
+ * Does NOT fire on the initial connection — only on reconnects.
91
+ * Returns an unsubscribe function. */
92
+ onReconnect(callback: () => void): () => void;
57
93
  /** Close all open WebSocket connections and reject pending calls. */
58
94
  closeAll(): void;
59
95
  }
@@ -23,6 +23,8 @@ export class ApiClient {
23
23
  // ── WebSocket RPC core ──────────────────────────────────────────────────
24
24
  this._ws = null;
25
25
  this._wsCallbacks = new Set();
26
+ this._reconnectCallbacks = new Set();
27
+ this._hasConnectedOnce = false;
26
28
  this._pendingCalls = new Map();
27
29
  this._wsReady = null;
28
30
  this._wsReadyResolve = null;
@@ -30,6 +32,7 @@ export class ApiClient {
30
32
  this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;
31
33
  this._wsClosed = false;
32
34
  this._wsPingTimer = null;
35
+ this._ignoredResponseIds = new Set();
33
36
  this.baseUrl = baseUrl;
34
37
  this.token = token;
35
38
  this._webSocketImpl = webSocketImpl;
@@ -64,7 +67,22 @@ export class ApiClient {
64
67
  this._wsReadyResolve = resolve;
65
68
  });
66
69
  const url = this._getWsUrl();
67
- const WsImpl = this._webSocketImpl ?? WebSocket;
70
+ // Fallback order: injected impl → globalThis.WebSocket (browsers, Node ≥ 22) → require('ws') (Node ≤ 20).
71
+ // globalThis lookup avoids a ReferenceError on Node 18 where `WebSocket` is not a global.
72
+ const globalWs = globalThis.WebSocket;
73
+ let WsImpl;
74
+ if (this._webSocketImpl) {
75
+ WsImpl = this._webSocketImpl;
76
+ }
77
+ else if (globalWs) {
78
+ WsImpl = globalWs;
79
+ }
80
+ else {
81
+ // Lazy CommonJS require so bundlers targeting browsers don't try to bundle `ws`.
82
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
83
+ const req = eval('require');
84
+ WsImpl = req('ws');
85
+ }
68
86
  const ws = new WsImpl(url);
69
87
  this._ws = ws;
70
88
  ws.onopen = () => {
@@ -74,6 +92,18 @@ export class ApiClient {
74
92
  this._wsReadyResolve = null;
75
93
  }
76
94
  this._startPing();
95
+ // Fire reconnect callbacks only on reconnect (not first connect)
96
+ if (this._hasConnectedOnce) {
97
+ for (const cb of this._reconnectCallbacks) {
98
+ try {
99
+ cb();
100
+ }
101
+ catch (e) {
102
+ console.error('Error in reconnect callback:', e);
103
+ }
104
+ }
105
+ }
106
+ this._hasConnectedOnce = true;
77
107
  };
78
108
  ws.onmessage = (event) => {
79
109
  let parsed;
@@ -102,6 +132,13 @@ export class ApiClient {
102
132
  }
103
133
  return;
104
134
  }
135
+ // Discard ack responses to cancel requests we sent — they have
136
+ // an id that was never in _pendingCalls, so without this guard
137
+ // they'd leak into subscriber callbacks as spurious events.
138
+ if (id && this._ignoredResponseIds.has(id)) {
139
+ this._ignoredResponseIds.delete(id);
140
+ return;
141
+ }
105
142
  // Server-push event (no id, or id not in pending) → route to subscribers
106
143
  for (const cb of this._wsCallbacks)
107
144
  cb(parsed);
@@ -158,40 +195,130 @@ export class ApiClient {
158
195
  if (this._wsReady)
159
196
  await this._wsReady;
160
197
  }
198
+ /**
199
+ * Like `_ready()`, but races the connection against an AbortSignal so
200
+ * that callers don't hang if the signal fires while connecting.
201
+ */
202
+ async _readyOrAbort(signal) {
203
+ if (signal?.aborted) {
204
+ throw new DOMException('Aborted', 'AbortError');
205
+ }
206
+ await new Promise((resolve, reject) => {
207
+ let settled = false;
208
+ const finish = (fn) => {
209
+ if (settled)
210
+ return;
211
+ settled = true;
212
+ if (signal && onAbort) {
213
+ signal.removeEventListener('abort', onAbort);
214
+ }
215
+ fn();
216
+ };
217
+ const onAbort = signal
218
+ ? () => finish(() => reject(new DOMException('Aborted', 'AbortError')))
219
+ : null;
220
+ if (onAbort) {
221
+ signal.addEventListener('abort', onAbort, { once: true });
222
+ }
223
+ this._ready().then(() => finish(resolve), (error) => finish(() => reject(error)));
224
+ });
225
+ }
161
226
  // ── RPC call method ─────────────────────────────────────────────────────
162
227
  /**
163
228
  * Send an RPC call over the WebSocket connection.
164
229
  * @param type - The operation type (e.g. 'agent.get', 'perspective.all')
165
230
  * @param params - Optional parameters to include in the message
166
- * @param timeoutMs - Optional per-call timeout override in ms. Defaults to
167
- * [[DEFAULT_TIMEOUT_MS]]. Use for long-running calls (LLM prompts,
168
- * holochain ops) that legitimately exceed the default.
231
+ * @param options - Optional call options: `signal` (AbortSignal for
232
+ * cancellation) and/or `timeoutMs` (per-call timeout override,
233
+ * defaults to [[DEFAULT_TIMEOUT_MS]] — use for long-running calls
234
+ * like LLM prompts or holochain ops that legitimately exceed it).
169
235
  * @returns Promise that resolves with the result from the server
170
236
  */
171
- async call(type, params, timeoutMs) {
172
- await this._ready();
237
+ async call(type, params, options) {
238
+ // Fast-path: if the caller already aborted, bail out before
239
+ // opening the socket. Matches fetch()'s behaviour.
240
+ const signal = options?.signal;
241
+ if (signal?.aborted) {
242
+ throw new DOMException('Aborted', 'AbortError');
243
+ }
244
+ await this._readyOrAbort(signal);
173
245
  const id = nextId();
174
246
  // Put params under a "params" key to avoid collision with
175
247
  // protocol fields "id" and "type" (e.g. params might contain
176
248
  // { id: modelId } or { type: "db" }).
177
249
  const message = { id, type, params: params || {} };
178
- const effectiveTimeout = timeoutMs ?? DEFAULT_TIMEOUT_MS;
250
+ const effectiveTimeout = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
179
251
  return new Promise((resolve, reject) => {
252
+ let abortHandler = null;
253
+ const cleanup = () => {
254
+ if (signal && abortHandler) {
255
+ signal.removeEventListener('abort', abortHandler);
256
+ abortHandler = null;
257
+ }
258
+ };
180
259
  const timer = setTimeout(() => {
181
260
  this._pendingCalls.delete(id);
261
+ cleanup();
182
262
  reject(new RpcError(408, `RPC call '${type}' timed out after ${effectiveTimeout}ms`));
183
263
  }, effectiveTimeout);
264
+ // Wrap resolve/reject so we always clean up the abort listener.
184
265
  this._pendingCalls.set(id, {
185
- resolve: resolve,
186
- reject,
266
+ resolve: (value) => { cleanup(); resolve(value); },
267
+ reject: (reason) => { cleanup(); reject(reason); },
187
268
  timer,
188
269
  });
270
+ if (signal) {
271
+ abortHandler = () => {
272
+ // Drop the pending entry first so the late server
273
+ // reply (if any) routes to the event subscribers,
274
+ // not to a stale resolver.
275
+ this._pendingCalls.delete(id);
276
+ clearTimeout(timer);
277
+ cleanup();
278
+ // Best-effort `request.cancel` — the executor will
279
+ // race the cancellation token against the in-flight
280
+ // handler. If the socket is already gone there's
281
+ // nothing useful we can send; the client side is
282
+ // still aborted either way.
283
+ if (this._ws && this._ws.readyState === 1 /* OPEN */) {
284
+ try {
285
+ const cancelId = nextId();
286
+ this._ignoredResponseIds.add(cancelId);
287
+ // Safety-net eviction: if the executor's ack never
288
+ // arrives (e.g. the socket drops right after we
289
+ // send request.cancel), the normal cleanup path
290
+ // (deleting the id when its response lands) never
291
+ // fires and the entry would live in this set for
292
+ // the lifetime of the client. Bound it instead —
293
+ // DEFAULT_TIMEOUT_MS is already the ceiling every
294
+ // other in-flight call uses, so an ack that hasn't
295
+ // shown up by then isn't coming.
296
+ setTimeout(() => {
297
+ this._ignoredResponseIds.delete(cancelId);
298
+ }, DEFAULT_TIMEOUT_MS);
299
+ this._ws.send(JSON.stringify({
300
+ id: cancelId,
301
+ type: 'request.cancel',
302
+ params: { targetId: id },
303
+ }));
304
+ }
305
+ catch (e) {
306
+ // Swallow — the user-visible failure mode is the
307
+ // AbortError below; a socket send failure here
308
+ // doesn't change client semantics.
309
+ }
310
+ }
311
+ reject(new DOMException('Aborted', 'AbortError'));
312
+ };
313
+ signal.addEventListener('abort', abortHandler, { once: true });
314
+ }
189
315
  if (this._ws && this._ws.readyState === 1 /* OPEN */) {
190
316
  this._ws.send(JSON.stringify(message));
191
317
  }
192
318
  else {
193
319
  this._pendingCalls.delete(id);
194
320
  clearTimeout(timer);
321
+ cleanup();
195
322
  reject(new RpcError(503, 'WebSocket not connected'));
196
323
  }
197
324
  });
@@ -229,6 +356,13 @@ export class ApiClient {
229
356
  this._wsReady = null;
230
357
  }
231
358
  }
359
+ /** Register a callback that fires after a successful WebSocket reconnect.
360
+ * Does NOT fire on the initial connection — only on reconnects.
361
+ * Returns an unsubscribe function. */
362
+ onReconnect(callback) {
363
+ this._reconnectCallbacks.add(callback);
364
+ return () => { this._reconnectCallbacks.delete(callback); };
365
+ }
232
366
  /** Close all open WebSocket connections and reject pending calls. */
233
367
  closeAll() {
234
368
  // Reject pending calls
@@ -239,5 +373,11 @@ export class ApiClient {
239
373
  this._pendingCalls.clear();
240
374
  this._closeWs();
241
375
  this._wsCallbacks.clear();
376
+ this._reconnectCallbacks.clear();
377
+ // Reset the first-connect gate so a reused client (closeAll() →
378
+ // later call()/subscribe() reopening via _ensureWs) does not fire
379
+ // freshly registered onReconnect callbacks on the initial open of
380
+ // the new connection — see the contract on onReconnect().
381
+ this._hasConnectedOnce = false;
242
382
  }
243
383
  }
@@ -18,6 +18,8 @@ export * from "./perspectives/PerspectiveHandle";
18
18
  export * from "./perspectives/PerspectiveProxy";
19
19
  export * from "./perspectives/AutoProcessor";
20
20
  export * from "./perspectives/InterpretationModels";
21
+ export * from "./perspectives/FlowModels";
22
+ export * from "./perspectives/FlowInstance";
21
23
  export * from "./perspectives/SparqlBindings";
22
24
  export * from "./perspectives/WakerSubscriptionManager";
23
25
  export * from "./perspectives/PerspectiveDiff";
@@ -35,7 +37,7 @@ export * from "./ai/Tasks";
35
37
  export * from "./runtime/RuntimeTypes";
36
38
  export { Model as AIModel, ModelApi, TokenizerSource, LocalModel, ModelType, ModelApiInput, TokenizerSourceInput, LocalModelInput, ModelInput, VoiceActivityParamsInput } from "./ai/AITypes";
37
39
  export * from './shacl/SHACLShape';
38
- export { SHACLFlow, FlowState, FlowTransition, LinkPattern, FlowableCondition } from './shacl/SHACLFlow';
40
+ export { SHACLFlow, FlowState, FlowTransition, LinkPattern, ModelQuery, PropertyCondition, ConsensusRule } from './shacl/SHACLFlow';
39
41
  export * from './shacl/NodeExpression';
40
42
  export * from './shacl/builders';
41
43
  export { fileToDataUri } from './shacl/index';
package/lib/src/index.js CHANGED
@@ -18,6 +18,8 @@ export * from "./perspectives/PerspectiveHandle";
18
18
  export * from "./perspectives/PerspectiveProxy";
19
19
  export * from "./perspectives/AutoProcessor";
20
20
  export * from "./perspectives/InterpretationModels";
21
+ export * from "./perspectives/FlowModels";
22
+ export * from "./perspectives/FlowInstance";
21
23
  export * from "./perspectives/SparqlBindings";
22
24
  export * from "./perspectives/WakerSubscriptionManager";
23
25
  export * from "./perspectives/PerspectiveDiff";
@@ -1,4 +1,5 @@
1
1
  import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
2
+ import { CallOptions } from "../apiClient";
2
3
  import type { SHACLShape } from "../shacl/SHACLShape";
3
4
  import type { JSONSchema, JSONSchemaToModelOptions } from "./json-schema";
4
5
  import { ModelQueryBuilder } from "./ModelQueryBuilder";
@@ -365,7 +366,7 @@ export declare class Ad4mModel {
365
366
  * });
366
367
  * ```
367
368
  */
368
- static findAll<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Q): Promise<(T & IncludeExtras<T, IncludeOf<Q>>)[]>;
369
+ static findAll<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Q, options?: CallOptions): Promise<(T & IncludeExtras<T, IncludeOf<Q>>)[]>;
369
370
  /**
370
371
  * Finds the first instance matching the query, or `null` if none exists.
371
372
  *
@@ -386,7 +387,7 @@ export declare class Ad4mModel {
386
387
  * }
387
388
  * ```
388
389
  */
389
- static findOne<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Q): Promise<(T & IncludeExtras<T, IncludeOf<Q>>) | null>;
390
+ static findOne<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Q, options?: CallOptions): Promise<(T & IncludeExtras<T, IncludeOf<Q>>) | null>;
390
391
  /**
391
392
  * Gets all instances with count of total matches without offset & limit applied.
392
393
  *
@@ -404,7 +405,7 @@ export declare class Ad4mModel {
404
405
  * console.log(`Showing 10 of ${totalCount} dessert recipes`);
405
406
  * ```
406
407
  */
407
- static findAllAndCount<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Q): Promise<ResultsWithTotalCount<T & IncludeExtras<T, IncludeOf<Q>>>>;
408
+ static findAllAndCount<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Q, options?: CallOptions): Promise<ResultsWithTotalCount<T & IncludeExtras<T, IncludeOf<Q>>>>;
408
409
  /**
409
410
  * Helper function for pagination with explicit page size and number.
410
411
  *
@@ -422,7 +423,7 @@ export declare class Ad4mModel {
422
423
  * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
423
424
  * ```
424
425
  */
425
- static paginate<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, pageSize: number, pageNumber: number, query?: Q): Promise<PaginationResult<T & IncludeExtras<T, IncludeOf<Q>>>>;
426
+ static paginate<T extends Ad4mModel, Q extends TypedQuery<T> = {}>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, pageSize: number, pageNumber: number, query?: Q, options?: CallOptions): Promise<PaginationResult<T & IncludeExtras<T, IncludeOf<Q>>>>;
426
427
  /**
427
428
  * Generates a SPARQL COUNT query for the model.
428
429
  *
@@ -447,7 +448,7 @@ export declare class Ad4mModel {
447
448
  * });
448
449
  * ```
449
450
  */
450
- static count<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: TypedQuery<T>): Promise<number>;
451
+ static count<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: TypedQuery<T>, options?: CallOptions): Promise<number>;
451
452
  private setProperty;
452
453
  /** Resolve a relation argument to a plain string ID. Accepts either a raw
453
454
  * string ID or an Ad4mModel instance (in which case `.id` is used). */