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

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 (97) hide show
  1. package/lib/index.cjs +610 -208
  2. package/lib/index.js +607 -209
  3. package/lib/src/Ad4mClient.d.ts +7 -0
  4. package/lib/src/Ad4mClient.js +9 -0
  5. package/lib/src/agent/AgentClient.d.ts +16 -1
  6. package/lib/src/agent/AgentClient.js +21 -2
  7. package/lib/src/ai/AITypes.d.ts +6 -2
  8. package/lib/src/apiClient.d.ts +13 -0
  9. package/lib/src/apiClient.js +67 -12
  10. package/lib/src/generated/api/Apps.d.ts +4 -0
  11. package/lib/src/generated/api/AuthInfo.d.ts +4 -0
  12. package/lib/src/generated/api/Events.d.ts +10 -12
  13. package/lib/src/generated/api/FlowStateChangedEvent.d.ts +3 -2
  14. package/lib/src/generated/api/Model.d.ts +4 -0
  15. package/lib/src/generated/api/ModelApi.d.ts +5 -1
  16. package/lib/src/generated/api/ModelApiInput.d.ts +7 -1
  17. package/lib/src/generated/api/Notification.d.ts +5 -1
  18. package/lib/src/generated/api/NotificationInput.d.ts +4 -0
  19. package/lib/src/generated/api/PerspectiveEvent.d.ts +8 -0
  20. package/lib/src/generated/api/{PerspectiveLinkWithOwner.d.ts → PerspectiveLinkEvent.d.ts} +4 -2
  21. package/lib/src/generated/api/{PerspectiveLinkUpdatedWithOwner.d.ts → PerspectiveLinkUpdatedEvent.d.ts} +4 -2
  22. package/lib/src/generated/api/PerspectiveRemovedEvent.d.ts +7 -0
  23. package/lib/src/generated/api/RequestCapabilityRequest.d.ts +1 -0
  24. package/lib/src/generated/api/RpcMethods.d.ts +10 -1
  25. package/lib/src/generated/api/RuntimeInfo.d.ts +5 -0
  26. package/lib/src/generated/api/RuntimeUpdateNotificationParams.d.ts +6 -1
  27. package/lib/src/generated/api/UsersRevokeAllSessionsParams.d.ts +7 -0
  28. package/{src/generated/api/PerspectiveRemovedWithOwner.ts → lib/src/generated/api/UsersRevokeAllSessionsParams.js} +1 -2
  29. package/lib/src/index.d.ts +1 -0
  30. package/lib/src/index.js +1 -0
  31. package/lib/src/model/Ad4mModel.js +45 -18
  32. package/lib/src/model/ModelQueryBuilder.d.ts +7 -3
  33. package/lib/src/model/ModelQueryBuilder.js +9 -4
  34. package/lib/src/model/query-common.js +7 -1
  35. package/lib/src/model/types.d.ts +45 -2
  36. package/lib/src/model/types.js +8 -0
  37. package/lib/src/perspectives/Container.d.ts +41 -0
  38. package/lib/src/perspectives/Container.js +62 -0
  39. package/lib/src/perspectives/PerspectiveProxy.d.ts +6 -3
  40. package/lib/src/perspectives/PerspectiveProxy.js +10 -4
  41. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +94 -12
  42. package/lib/src/perspectives/WakerSubscriptionManager.js +276 -75
  43. package/lib/src/runtime/RuntimeClient.d.ts +6 -3
  44. package/lib/src/runtime/RuntimeClient.js +2 -0
  45. package/lib/src/runtime/RuntimeTypes.d.ts +7 -1
  46. package/package.json +2 -2
  47. package/src/Ad4mClient.test.ts +54 -19
  48. package/src/Ad4mClient.ts +10 -0
  49. package/src/agent/AgentClient.ts +26 -2
  50. package/src/ai/AITypes.ts +6 -2
  51. package/src/apiClient.test.ts +128 -3
  52. package/src/apiClient.ts +64 -11
  53. package/src/generated/api/Apps.ts +6 -1
  54. package/src/generated/api/AuthInfo.ts +6 -1
  55. package/src/generated/api/Events.ts +10 -12
  56. package/src/generated/api/FlowStateChangedEvent.ts +3 -2
  57. package/src/generated/api/Model.ts +4 -0
  58. package/src/generated/api/ModelApi.ts +5 -1
  59. package/src/generated/api/ModelApiInput.ts +8 -1
  60. package/src/generated/api/Notification.ts +5 -1
  61. package/src/generated/api/NotificationInput.ts +6 -1
  62. package/src/generated/api/PerspectiveEvent.ts +7 -0
  63. package/src/generated/api/{PerspectiveLinkUpdatedWithOwner.ts → PerspectiveLinkEvent.ts} +4 -1
  64. package/src/generated/api/PerspectiveLinkUpdatedEvent.ts +7 -0
  65. package/src/generated/api/PerspectiveRemovedEvent.ts +6 -0
  66. package/src/generated/api/RequestCapabilityRequest.ts +1 -1
  67. package/src/generated/api/RpcMethods.ts +4 -1
  68. package/src/generated/api/RuntimeInfo.ts +6 -1
  69. package/src/generated/api/RuntimeUpdateNotificationParams.ts +7 -1
  70. package/src/generated/api/UsersRevokeAllSessionsParams.ts +8 -0
  71. package/src/index.ts +1 -0
  72. package/src/model/Ad4mModel.ts +51 -19
  73. package/src/model/ModelQueryBuilder.ts +9 -6
  74. package/src/model/containment-scope.test.ts +104 -0
  75. package/src/model/query-common.ts +10 -1
  76. package/src/model/types.ts +56 -2
  77. package/src/perspectives/Container.test.ts +65 -0
  78. package/src/perspectives/Container.ts +46 -0
  79. package/src/perspectives/PerspectiveProxy.test.ts +11 -0
  80. package/src/perspectives/PerspectiveProxy.ts +10 -4
  81. package/src/perspectives/WakerSubscriptionManager.test.ts +400 -82
  82. package/src/perspectives/WakerSubscriptionManager.ts +321 -85
  83. package/src/perspectives/link-updated-type.test.ts +2 -2
  84. package/src/perspectives/listener-leaks.test.ts +3 -3
  85. package/src/runtime/RuntimeClient.ts +6 -3
  86. package/src/runtime/RuntimeTypes.ts +10 -1
  87. package/lib/src/generated/api/MessageReceivedEvent.d.ts +0 -7
  88. package/lib/src/generated/api/PerspectiveRemovedWithOwner.d.ts +0 -5
  89. package/lib/src/generated/api/PerspectiveWithOwner.d.ts +0 -6
  90. package/lib/src/generated/api/PerspectiveWithOwner.js +0 -1
  91. package/src/generated/api/MessageReceivedEvent.ts +0 -7
  92. package/src/generated/api/PerspectiveLinkWithOwner.ts +0 -4
  93. package/src/generated/api/PerspectiveWithOwner.ts +0 -4
  94. /package/lib/src/generated/api/{MessageReceivedEvent.js → PerspectiveEvent.js} +0 -0
  95. /package/lib/src/generated/api/{PerspectiveLinkUpdatedWithOwner.js → PerspectiveLinkEvent.js} +0 -0
  96. /package/lib/src/generated/api/{PerspectiveLinkWithOwner.js → PerspectiveLinkUpdatedEvent.js} +0 -0
  97. /package/lib/src/generated/api/{PerspectiveRemovedWithOwner.js → PerspectiveRemovedEvent.js} +0 -0
package/lib/index.js CHANGED
@@ -137,7 +137,12 @@ function nextId() {
137
137
  * for the next socket is safe for writes too. This covers an executor that
138
138
  * is still binding its port (about 1.5 s with the reconnect backoff). */
139
139
  const MAX_CONNECT_ATTEMPTS = 3;
140
- const closedError = () => new RpcError(503, 'WebSocket connection closed');
140
+ const closedError = (reason) => new RpcError(503, reason || 'WebSocket connection closed');
141
+ /** Close code for "try again later": the executor's wallet is locked, so it cannot check the
142
+ * token yet. The token may be good: reconnect as for any close, and pass the reason on. */
143
+ const CLOSE_TRY_AGAIN_LATER = 1013;
144
+ /** Close code the executor uses when the socket's token opens no session, expired or was revoked. */
145
+ const CLOSE_AUTH_FAILED = 1008;
141
146
  class ApiClient {
142
147
  constructor(baseUrl, token, webSocketImpl, fetchImpl) {
143
148
  // ── WebSocket ───────────────────────────────────────────────────────────
@@ -148,6 +153,10 @@ class ApiClient {
148
153
  /** `on()` handlers by event type; a type with none has no entry. */
149
154
  this._handlers = new Map();
150
155
  this._reconnectCallbacks = new Set();
156
+ this._authFailedCallbacks = new Set();
157
+ /** Set once the executor refused the token: the reason. The client then
158
+ * never connects again; a new token needs a new client. */
159
+ this._authFailed = null;
151
160
  this._hasConnectedOnce = false;
152
161
  this._pendingCalls = new Map();
153
162
  this._wsReconnectTimer = null;
@@ -183,6 +192,8 @@ class ApiClient {
183
192
  _ensureWs() {
184
193
  if (this._ws)
185
194
  return;
195
+ if (this._authFailed !== null)
196
+ throw new RpcError(401, this._authFailed);
186
197
  const WsImpl = this._webSocketImpl ?? globalThis.WebSocket;
187
198
  const ws = new WsImpl(this._getWsUrl());
188
199
  this._ws = ws;
@@ -191,9 +202,17 @@ class ApiClient {
191
202
  resolve();
192
203
  this._onOpen(ws);
193
204
  };
194
- ws.onclose = () => {
195
- reject(closedError());
196
- this._onClose(ws);
205
+ ws.onclose = (event) => {
206
+ // Classify the close for watchApplied() as for every other waiting call.
207
+ reject(event?.code === CLOSE_AUTH_FAILED
208
+ ? new RpcError(401, event.reason || 'token expired or revoked')
209
+ : closedError(event?.code === CLOSE_TRY_AGAIN_LATER ? event.reason : undefined));
210
+ if (event?.code === CLOSE_AUTH_FAILED && this._ws === ws) {
211
+ this._failAuth(event.reason || 'Unauthorized access: the token expired or was revoked');
212
+ }
213
+ else {
214
+ this._onClose(ws, event?.code === CLOSE_TRY_AGAIN_LATER ? event.reason : undefined);
215
+ }
197
216
  };
198
217
  });
199
218
  // Only watchApplied() awaits this; a close before open is not an error otherwise.
@@ -213,10 +232,15 @@ class ApiClient {
213
232
  if (!pending)
214
233
  return; // late reply to a timed-out or aborted call, or a cancel ack
215
234
  const error = parsed.error;
216
- if (error)
217
- pending.reject(new RpcError(error.code ?? 500, error.message ?? 'Unknown error'));
218
- else
235
+ if (!error) {
219
236
  pending.resolve(parsed.result);
237
+ return;
238
+ }
239
+ const rpcError = new RpcError(error.code ?? 500, error.message ?? 'Unknown error');
240
+ pending.reject(rpcError);
241
+ // The executor answers 401 only when the token stopped working, then closes the socket.
242
+ if (rpcError.status === 401)
243
+ this._failAuth(rpcError.body);
220
244
  return;
221
245
  }
222
246
  if (parsed.type === 'pong')
@@ -265,7 +289,8 @@ class ApiClient {
265
289
  }
266
290
  this._hasConnectedOnce = true;
267
291
  }
268
- _onClose(ws) {
292
+ /** `reason` is set when the executor asked to try again later; calls that fail carry it. */
293
+ _onClose(ws, reason) {
269
294
  // A socket closed by _closeWs() can report after a new one exists.
270
295
  if (this._ws !== ws)
271
296
  return;
@@ -280,12 +305,25 @@ class ApiClient {
280
305
  pending.retry = false;
281
306
  }
282
307
  else {
283
- pending.reject(closedError());
308
+ pending.reject(closedError(reason));
284
309
  }
285
310
  }
286
311
  if (this._handlers.size > 0 || this._pendingCalls.size > 0)
287
312
  this._scheduleReconnect();
288
313
  }
314
+ /** The executor refused the token: fail every call with 401, stop
315
+ * reconnecting and tell the `onAuthFailed` callbacks, once. */
316
+ _failAuth(reason) {
317
+ if (this._authFailed !== null)
318
+ return;
319
+ this._authFailed = reason;
320
+ const error = new RpcError(401, reason);
321
+ for (const pending of this._pendingCalls.values())
322
+ pending.reject(error);
323
+ this._closeWs();
324
+ for (const cb of [...this._authFailedCallbacks])
325
+ callSafely(cb, 'Error in auth-failed callback:', reason);
326
+ }
289
327
  _startPing() {
290
328
  this._stopPing();
291
329
  this._wsPingTimer = setInterval(() => {
@@ -301,7 +339,7 @@ class ApiClient {
301
339
  }
302
340
  }
303
341
  _scheduleReconnect() {
304
- if (this._wsReconnectTimer)
342
+ if (this._wsReconnectTimer || this._authFailed !== null)
305
343
  return;
306
344
  const delay = this._wsReconnectDelay;
307
345
  this._wsReconnectDelay = Math.min(this._wsReconnectDelay * 2, MAX_RECONNECT_DELAY_MS);
@@ -401,7 +439,9 @@ class ApiClient {
401
439
  regs.add(reg);
402
440
  this._scheduleWatch();
403
441
  }
404
- this._ensureWs();
442
+ // A client whose token was refused keeps the handler but opens no socket.
443
+ if (this._authFailed === null)
444
+ this._ensureWs();
405
445
  return () => {
406
446
  const regs = this._handlers.get(type);
407
447
  if (!regs?.delete(reg))
@@ -468,10 +508,13 @@ class ApiClient {
468
508
  if (key === this._watching)
469
509
  return;
470
510
  this._watching = key;
471
- this._watchSent = this._request('events.watch', events).then(() => { this._watchRetries = 0; }, (e) => {
511
+ const sent = this._request('events.watch', events).then(() => { this._watchRetries = 0; }, (e) => {
472
512
  if (this._watching !== key)
473
513
  return;
474
514
  this._watching = null;
515
+ // A refused token (401) gets no next socket: watchApplied() must not resolve.
516
+ if (e instanceof RpcError && e.status === 401)
517
+ throw e;
475
518
  // A closed socket (503) gets the watch again when the next one opens.
476
519
  if (e instanceof RpcError && e.status === 503)
477
520
  return;
@@ -483,6 +526,9 @@ class ApiClient {
483
526
  }, WATCH_RETRY_DELAY_MS);
484
527
  }
485
528
  });
529
+ // Only watchApplied() awaits this; a refused watch is not an unhandled rejection otherwise.
530
+ sent.catch(() => { });
531
+ this._watchSent = sent;
486
532
  }
487
533
  _closeWs() {
488
534
  this._stopPing();
@@ -506,6 +552,14 @@ class ApiClient {
506
552
  this._reconnectCallbacks.add(callback);
507
553
  return () => { this._reconnectCallbacks.delete(callback); };
508
554
  }
555
+ /** Register a callback that fires once when the executor refuses this
556
+ * client's token: a 401 reply, or a socket closed with code 1008. Every
557
+ * call then fails with a 401 `RpcError` and the client does not reconnect;
558
+ * build a new client to use another token. Returns an unsubscribe function. */
559
+ onAuthFailed(callback) {
560
+ this._authFailedCallbacks.add(callback);
561
+ return () => { this._authFailedCallbacks.delete(callback); };
562
+ }
509
563
  /** Close the WebSocket and reject pending calls. */
510
564
  closeAll() {
511
565
  for (const pending of this._pendingCalls.values()) {
@@ -514,6 +568,7 @@ class ApiClient {
514
568
  this._closeWs();
515
569
  this._handlers.clear();
516
570
  this._reconnectCallbacks.clear();
571
+ this._authFailedCallbacks.clear();
517
572
  // A reused client must not fire onReconnect on its next first open.
518
573
  this._hasConnectedOnce = false;
519
574
  }
@@ -1237,8 +1292,15 @@ class AgentClient {
1237
1292
  async entanglementProofPreFlight(deviceKey, deviceKeyType) {
1238
1293
  return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('agent.entanglementProofPreflight', { deviceKey, deviceKeyType });
1239
1294
  }
1240
- async requestCapability(authInfo) {
1241
- return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('agent.requestCapability', { authInfo });
1295
+ /**
1296
+ * Asks the executor for a capability token. `agent` names the agent the token will act
1297
+ * as: a managed user's email or an agent's DID; absent, the executor's main agent. That
1298
+ * agent's owner approves the request (the operator for the main agent, the user for
1299
+ * theirs). Returns the request id that {@link generateJwt} redeems with the approver's
1300
+ * six-digit code.
1301
+ */
1302
+ async requestCapability(authInfo, agent) {
1303
+ return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('agent.requestCapability', agent === undefined ? { authInfo } : { authInfo, agent });
1242
1304
  }
1243
1305
  async permitCapability(auth) {
1244
1306
  return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('agent.permitCapability', { auth });
@@ -1274,6 +1336,18 @@ class AgentClient {
1274
1336
  async verifyEmailCode(email, code, verificationType) {
1275
1337
  return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('user.verifyEmail', { email, code, verificationType });
1276
1338
  }
1339
+ /** Revokes this client's user token. The executor then closes the client's sockets. */
1340
+ async logout() {
1341
+ return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('user.logout', {});
1342
+ }
1343
+ /**
1344
+ * Revokes every token of a user issued up to now, this client's own included, and closes
1345
+ * their sockets. A user leaves out `email` (or names themselves); the operator names the
1346
+ * user. Needs AGENT_UPDATE, which a login holds. Tokens from a later login work.
1347
+ */
1348
+ async revokeAllSessions(email) {
1349
+ return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('user.revokeAllSessions', email === undefined ? {} : { email });
1350
+ }
1277
1351
  // Hosting methods
1278
1352
  async hostingUserInfo() {
1279
1353
  const info = (await __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('hosting.info', {})).userInfo ?? {
@@ -7487,7 +7561,7 @@ function extractNamespaceFromUri(uri) {
7487
7561
  return uri.substring(0, colonIdx + 1);
7488
7562
  return uri;
7489
7563
  }
7490
- /** A live SPARQL query with its latest result.
7564
+ /** A live SPARQL or model query with its latest result.
7491
7565
  *
7492
7566
  * `subscribe()` opens the query and resolves once the first result is in;
7493
7567
  * `onResult()` callbacks then get every later result. The executor sends
@@ -7501,14 +7575,20 @@ function extractNamespaceFromUri(uri) {
7501
7575
  * ```
7502
7576
  */
7503
7577
  class QuerySubscriptionProxy {
7504
- constructor(uuid, query, client) {
7578
+ /** With `className`, `query` is a model query (JSON) over that class or
7579
+ * union of classes, opened with `modelSubscribe`; results are
7580
+ * `{ instances, totalCount }`. Without it, `query` is SPARQL. */
7581
+ constructor(uuid, query, client, className) {
7505
7582
  _QuerySubscriptionProxy_instances.add(this);
7506
7583
  _QuerySubscriptionProxy_live.set(this, void 0);
7507
7584
  _QuerySubscriptionProxy_callbacks.set(this, new Set());
7508
7585
  _QuerySubscriptionProxy_initialized.set(this, void 0);
7509
7586
  _QuerySubscriptionProxy_initResolve.set(this, void 0);
7510
7587
  _QuerySubscriptionProxy_initReject.set(this, void 0);
7511
- __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_live, new LiveQuery(client, uuid, () => client.subscribeQuery(uuid, query), result => __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliver).call(this, result)), "f");
7588
+ const open = className === undefined
7589
+ ? () => client.subscribeQuery(uuid, query)
7590
+ : () => client.modelSubscribe(uuid, className, query);
7591
+ __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_live, new LiveQuery(client, uuid, open, result => __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliver).call(this, result)), "f");
7512
7592
  __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_initialized, new Promise((resolve, reject) => {
7513
7593
  __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_initResolve, resolve, "f");
7514
7594
  __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_initReject, reject, "f");
@@ -7930,7 +8010,7 @@ class PerspectiveProxy {
7930
8010
  *
7931
8011
  * The state is not stored on the graph: the engine derives it from the
7932
8012
  * signed proposals and keeps what it derived per agent, outside the
7933
- * perspective. So no other agent — a co-owner on the same node included —
8013
+ * perspective. So no other agent — a co-owner on the same executor included —
7934
8014
  * can read or write your entries, and a link query never sees them.
7935
8015
  * `FlowInstance.findAll` / `start` call this for you.
7936
8016
  */
@@ -9907,6 +9987,8 @@ class RuntimeClient {
9907
9987
  async removeKnownLinkLanguageTemplates(addresses) {
9908
9988
  return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, "f").call('runtime.removeLinkLanguageTemplates', { addresses });
9909
9989
  }
9990
+ /** Every link-language template the executor knows, with its meta (name, description,
9991
+ * `possibleTemplateParams`). A template whose meta cannot be read is left out. */
9910
9992
  async knownLinkLanguageTemplates() {
9911
9993
  return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, "f").call('runtime.linkLanguageTemplates', {});
9912
9994
  }
@@ -17450,6 +17532,14 @@ _AIClient_apiClient = new WeakMap(), _AIClient_transcriptionUnsubscribers = new
17450
17532
  * (`query-utils.ts`, `decorators.ts`, etc.) can import types without
17451
17533
  * creating circular runtime dependencies on `Ad4mModel.ts`.
17452
17534
  */
17535
+ /** Whether this traversal follows containment rather than a named predicate. */
17536
+ function isContainmentTraversal(scope) {
17537
+ return isTraverseScope(scope) && !('predicate' in scope && scope.predicate) && !('model' in scope && scope.model);
17538
+ }
17539
+ /** Whether this scope is the containment form, `{ id }` alone. */
17540
+ function isContainedScope(scope) {
17541
+ return !isTraverseScope(scope) && !('predicate' in scope) && !('model' in scope);
17542
+ }
17453
17543
  /**
17454
17544
  * Whether this scope is a traversal rather than a single named parent.
17455
17545
  *
@@ -17495,6 +17585,12 @@ function resolveParentPredicate(parent, childCtor) {
17495
17585
  // Raw form — explicit predicate
17496
17586
  if ('predicate' in parent)
17497
17587
  return parent.predicate;
17588
+ // Containment form — one predicate per containment edge, resolved by the
17589
+ // executor from the installed classes. There is no single one to return.
17590
+ if (isContainedScope(parent) || isContainmentTraversal(parent)) {
17591
+ throw new Error('parent(): a containment scope { id } names no single predicate; the executor resolves ' +
17592
+ 'it. Use the model query path (findAll / query / subscribe) to read it.');
17593
+ }
17498
17594
  // Model form — resolve from relation metadata
17499
17595
  const { model } = parent;
17500
17596
  const relMeta = getRelationsMetadata(model);
@@ -18620,9 +18716,10 @@ class ModelQueryBuilder {
18620
18716
  * 3. **String id + model class** — same metadata scan (or field lookup if
18621
18717
  * options include `field`).
18622
18718
  * 4. **String id + string predicate** — raw escape hatch, no metadata lookup.
18623
- *
18624
- * Passing a plain string id with no second argument throws because the
18625
- * predicate cannot be resolved without a model class.
18719
+ * 5. **String id alone** — containment through the built-in `Container`:
18720
+ * the id's `ad4m://has_child` targets, and the targets of the `children`
18721
+ * relation of every class the id is an instance of. The executor
18722
+ * resolves the predicates; nothing is looked up here.
18626
18723
  *
18627
18724
  * @param idOrInstance - The parent's expression URI **or** an Ad4mModel instance
18628
18725
  * @param modelOrPredicate - A model class (predicate auto-resolved) **or** a raw predicate string
@@ -18645,6 +18742,9 @@ class ModelQueryBuilder {
18645
18742
  *
18646
18743
  * // String id + raw predicate (escape hatch)
18647
18744
  * Recipe.query(perspective).parent(cookbookId, "cookbook://recipe").get();
18745
+ *
18746
+ * // String id alone: whatever cookbookId contains
18747
+ * Recipe.query(perspective).parent(cookbookId).get();
18648
18748
  * ```
18649
18749
  */
18650
18750
  parent(idOrInstance, modelOrPredicate, options) {
@@ -18672,7 +18772,8 @@ class ModelQueryBuilder {
18672
18772
  this.queryParams.parent = { id, model: idOrInstance.constructor, ...(field && { field }) };
18673
18773
  }
18674
18774
  else {
18675
- throw new Error('parent() called with a string id requires a second argument: either a model class or a predicate string');
18775
+ // String id alone → containment form of Scope
18776
+ this.queryParams.parent = { id };
18676
18777
  }
18677
18778
  return this;
18678
18779
  }
@@ -19471,6 +19572,24 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
19471
19572
  }
19472
19573
  return instance;
19473
19574
  }
19575
+ /**
19576
+ * Put `childId` under `parent`. A containment scope `{ id }` writes through the
19577
+ * built-in `Container` (#1446): the executor runs the adder of the parent's own
19578
+ * `children` relation when its class has one (a block's `we://child`), else
19579
+ * writes `ad4m://has_child`. The other forms write their one predicate.
19580
+ */
19581
+ async function linkToParent(perspective, parent, childCtor, childId, batchId) {
19582
+ if (isContainedScope(parent)) {
19583
+ await perspective.updateSubject("ad4m://Container", parent.id, { children: { action: "adder", value: [childId] } }, batchId);
19584
+ return;
19585
+ }
19586
+ const link = new Link({
19587
+ source: parent.id,
19588
+ predicate: resolveParentPredicate(parent, childCtor),
19589
+ target: childId,
19590
+ });
19591
+ await perspective.add(link, 'shared', batchId);
19592
+ }
19474
19593
  /**
19475
19594
  * Base class for defining data models in AD4M.
19476
19595
  *
@@ -20128,7 +20247,28 @@ class Ad4mModel {
20128
20247
  query = { ...query, include: { ...expanded, ...query.include } };
20129
20248
  }
20130
20249
  const queryInput = {};
20131
- if (query.parent) {
20250
+ if (query.parent && isContainedScope(query.parent)) {
20251
+ // Containment: the executor resolves the predicates from the installed
20252
+ // classes, so only the id travels.
20253
+ queryInput.parent = { id: query.parent.id };
20254
+ }
20255
+ else if (query.parent && isContainmentTraversal(query.parent)) {
20256
+ // A traversal over containment: no predicate travels either.
20257
+ const t = query.parent;
20258
+ const traverse = { ids: t.ids };
20259
+ if (t.transitive !== undefined)
20260
+ traverse.transitive = t.transitive;
20261
+ if (t.direction !== undefined)
20262
+ traverse.direction = t.direction;
20263
+ if (t.limitPerAnchor !== undefined)
20264
+ traverse.limitPerAnchor = t.limitPerAnchor;
20265
+ if (t.levels !== undefined)
20266
+ traverse.levels = t.levels;
20267
+ if (t.maxDepth !== undefined)
20268
+ traverse.maxDepth = t.maxDepth;
20269
+ queryInput.parent = traverse;
20270
+ }
20271
+ else if (query.parent) {
20132
20272
  const parentPredicate = resolveParentPredicate(query.parent, this);
20133
20273
  // A traversal keeps its own shape on the wire: the executor reads `ids`,
20134
20274
  // and flattening it to one `id` here is how a request for a whole level
@@ -20152,6 +20292,8 @@ class Ad4mModel {
20152
20292
  traverse.limitPerAnchor = t.limitPerAnchor;
20153
20293
  if (t.levels !== undefined)
20154
20294
  traverse.levels = t.levels;
20295
+ if (t.maxDepth !== undefined)
20296
+ traverse.maxDepth = t.maxDepth;
20155
20297
  queryInput.parent = traverse;
20156
20298
  }
20157
20299
  else {
@@ -21116,14 +21258,7 @@ class Ad4mModel {
21116
21258
  if (options?.parent && !options?.batchId) {
21117
21259
  const batchId = await perspective.createBatch();
21118
21260
  await instance.save(batchId);
21119
- const parent = requireSingleParent(options.parent);
21120
- const predicate = resolveParentPredicate(parent, this);
21121
- const link = new Link({
21122
- source: parent.id,
21123
- predicate,
21124
- target: instance.id,
21125
- });
21126
- await perspective.add(link, 'shared', batchId);
21261
+ await linkToParent(perspective, requireSingleParent(options.parent), this, instance.id, batchId);
21127
21262
  await perspective.commitBatch(batchId);
21128
21263
  // Hydrate the instance now that the batch has been committed (mirrors the
21129
21264
  // behaviour of save() when it manages its own batch).
@@ -21133,14 +21268,7 @@ class Ad4mModel {
21133
21268
  await instance.save(options?.batchId);
21134
21269
  // Create parent → child link if a parent scope was provided
21135
21270
  if (options?.parent) {
21136
- const parent = requireSingleParent(options.parent);
21137
- const predicate = resolveParentPredicate(parent, this);
21138
- const link = new Link({
21139
- source: parent.id,
21140
- predicate,
21141
- target: instance.id,
21142
- });
21143
- await perspective.add(link, 'shared', options?.batchId);
21271
+ await linkToParent(perspective, requireSingleParent(options.parent), this, instance.id, options?.batchId);
21144
21272
  }
21145
21273
  return instance;
21146
21274
  }
@@ -21547,6 +21675,15 @@ class Ad4mClient {
21547
21675
  on(type, handler, filter) {
21548
21676
  return __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f").on(type, handler, filter);
21549
21677
  }
21678
+ /**
21679
+ * Call `callback` once when the executor refuses this client's token
21680
+ * (expired, revoked, or no session). Every call then fails with a 401
21681
+ * `RpcError` and the client stops reconnecting: log in again and build a
21682
+ * new client. Returns a function that removes the callback.
21683
+ */
21684
+ onAuthFailed(callback) {
21685
+ return __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f").onAuthFailed(callback);
21686
+ }
21550
21687
  /** Close all event connections and clear in-memory caches */
21551
21688
  close() {
21552
21689
  __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f").clearByDidCache();
@@ -21698,13 +21835,13 @@ class LanguageLanguageInput {
21698
21835
  * const runs = await InterpretationRun.findAll(perspective);
21699
21836
  * const configs = await AutoProcessorConfig.findAll(perspective);
21700
21837
  */
21701
- var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
21838
+ var __decorate$3 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
21702
21839
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
21703
21840
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21704
21841
  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;
21705
21842
  return c > 3 && r && Object.defineProperty(target, key, r), r;
21706
21843
  };
21707
- var __metadata$2 = (undefined && undefined.__metadata) || function (k, v) {
21844
+ var __metadata$3 = (undefined && undefined.__metadata) || function (k, v) {
21708
21845
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
21709
21846
  };
21710
21847
  // ── AutoProcessorConfig ─────────────────────────────────────────────────────
@@ -21745,71 +21882,71 @@ let AutoProcessorConfig = class AutoProcessorConfig extends Ad4mModel {
21745
21882
  // `batchMax` + `claimTtlMs` — the Rust SDNA takes the same shape.
21746
21883
  }
21747
21884
  };
21748
- __decorate$2([
21885
+ __decorate$3([
21749
21886
  Property({ through: "ad4m://processor_id", required: true, identity: true }),
21750
- __metadata$2("design:type", String)
21887
+ __metadata$3("design:type", String)
21751
21888
  ], AutoProcessorConfig.prototype, "processorId", void 0);
21752
- __decorate$2([
21889
+ __decorate$3([
21753
21890
  Property({ through: "ad4m://source_scope_query", required: true }),
21754
- __metadata$2("design:type", String)
21891
+ __metadata$3("design:type", String)
21755
21892
  ], AutoProcessorConfig.prototype, "sourceScopeQuery", void 0);
21756
- __decorate$2([
21893
+ __decorate$3([
21757
21894
  Optional({ through: "ad4m://base_prefix" }),
21758
- __metadata$2("design:type", String)
21895
+ __metadata$3("design:type", String)
21759
21896
  ], AutoProcessorConfig.prototype, "basePrefix", void 0);
21760
- __decorate$2([
21897
+ __decorate$3([
21761
21898
  HasMany({ through: "ad4m://interpretation_class", datatype: "xsd:string" }),
21762
- __metadata$2("design:type", Array)
21899
+ __metadata$3("design:type", Array)
21763
21900
  ], AutoProcessorConfig.prototype, "interpretationClasses", void 0);
21764
- __decorate$2([
21901
+ __decorate$3([
21765
21902
  HasMany({ through: "ad4m://flow", datatype: "xsd:string" }),
21766
- __metadata$2("design:type", Array)
21903
+ __metadata$3("design:type", Array)
21767
21904
  ], AutoProcessorConfig.prototype, "flows", void 0);
21768
- __decorate$2([
21905
+ __decorate$3([
21769
21906
  Property({ through: "ad4m://debounce_ms", required: true }),
21770
- __metadata$2("design:type", String)
21907
+ __metadata$3("design:type", String)
21771
21908
  ], AutoProcessorConfig.prototype, "debounceMs", void 0);
21772
- __decorate$2([
21909
+ __decorate$3([
21773
21910
  Optional({ through: "ad4m://batch_min" }),
21774
- __metadata$2("design:type", String)
21911
+ __metadata$3("design:type", String)
21775
21912
  ], AutoProcessorConfig.prototype, "batchMin", void 0);
21776
- __decorate$2([
21913
+ __decorate$3([
21777
21914
  Property({ through: "ad4m://batch_max", required: true }),
21778
- __metadata$2("design:type", String)
21915
+ __metadata$3("design:type", String)
21779
21916
  ], AutoProcessorConfig.prototype, "batchMax", void 0);
21780
- __decorate$2([
21917
+ __decorate$3([
21781
21918
  Optional({ through: "ad4m://max_wait_ms" }),
21782
- __metadata$2("design:type", String)
21919
+ __metadata$3("design:type", String)
21783
21920
  ], AutoProcessorConfig.prototype, "maxWaitMs", void 0);
21784
- __decorate$2([
21921
+ __decorate$3([
21785
21922
  Property({ through: "ad4m://claim_ttl_ms", required: true }),
21786
- __metadata$2("design:type", String)
21923
+ __metadata$3("design:type", String)
21787
21924
  ], AutoProcessorConfig.prototype, "claimTtlMs", void 0);
21788
- __decorate$2([
21925
+ __decorate$3([
21789
21926
  Optional({ through: "ad4m://source_window_ms" }),
21790
- __metadata$2("design:type", String)
21927
+ __metadata$3("design:type", String)
21791
21928
  ], AutoProcessorConfig.prototype, "sourceWindowMs", void 0);
21792
- __decorate$2([
21929
+ __decorate$3([
21793
21930
  Optional({ through: "ad4m://dedup_strategy" }),
21794
- __metadata$2("design:type", String)
21931
+ __metadata$3("design:type", String)
21795
21932
  ], AutoProcessorConfig.prototype, "dedupStrategy", void 0);
21796
- __decorate$2([
21933
+ __decorate$3([
21797
21934
  Optional({ through: "ad4m://existing_scope" }),
21798
- __metadata$2("design:type", String)
21935
+ __metadata$3("design:type", String)
21799
21936
  ], AutoProcessorConfig.prototype, "existingScope", void 0);
21800
- __decorate$2([
21937
+ __decorate$3([
21801
21938
  Optional({ through: "ad4m://mint_scope" }),
21802
- __metadata$2("design:type", String)
21939
+ __metadata$3("design:type", String)
21803
21940
  ], AutoProcessorConfig.prototype, "mintScope", void 0);
21804
- __decorate$2([
21941
+ __decorate$3([
21805
21942
  Optional({ through: "ad4m://max_tool_calls" }),
21806
- __metadata$2("design:type", String)
21943
+ __metadata$3("design:type", String)
21807
21944
  ], AutoProcessorConfig.prototype, "maxToolCalls", void 0);
21808
- __decorate$2([
21945
+ __decorate$3([
21809
21946
  Optional({ through: "ad4m://emit_debug_events", resolveLanguage: "literal" }),
21810
- __metadata$2("design:type", String)
21947
+ __metadata$3("design:type", String)
21811
21948
  ], AutoProcessorConfig.prototype, "emitDebugEvents", void 0);
21812
- AutoProcessorConfig = __decorate$2([
21949
+ AutoProcessorConfig = __decorate$3([
21813
21950
  Model$1({ name: "AutoProcessor" })
21814
21951
  ], AutoProcessorConfig);
21815
21952
  // ── InterpretationRun ───────────────────────────────────────────────────────
@@ -21833,39 +21970,39 @@ let InterpretationRun = class InterpretationRun extends Ad4mModel {
21833
21970
  this.sources = [];
21834
21971
  }
21835
21972
  };
21836
- __decorate$2([
21973
+ __decorate$3([
21837
21974
  Property({ through: "ad4m://interp/run_id", required: true, identity: true }),
21838
- __metadata$2("design:type", String)
21975
+ __metadata$3("design:type", String)
21839
21976
  ], InterpretationRun.prototype, "runId", void 0);
21840
- __decorate$2([
21977
+ __decorate$3([
21841
21978
  Optional({ through: "ad4m://interp/model" }),
21842
- __metadata$2("design:type", String)
21979
+ __metadata$3("design:type", String)
21843
21980
  ], InterpretationRun.prototype, "model", void 0);
21844
- __decorate$2([
21981
+ __decorate$3([
21845
21982
  Optional({ through: "ad4m://interp/prompt_version" }),
21846
- __metadata$2("design:type", String)
21983
+ __metadata$3("design:type", String)
21847
21984
  ], InterpretationRun.prototype, "promptVersion", void 0);
21848
- __decorate$2([
21985
+ __decorate$3([
21849
21986
  Optional({ through: "ad4m://interp/ran_at" }),
21850
- __metadata$2("design:type", String)
21987
+ __metadata$3("design:type", String)
21851
21988
  ], InterpretationRun.prototype, "ranAt", void 0);
21852
- __decorate$2([
21989
+ __decorate$3([
21853
21990
  Optional({ through: "ad4m://interp/processor" }),
21854
- __metadata$2("design:type", String)
21991
+ __metadata$3("design:type", String)
21855
21992
  ], InterpretationRun.prototype, "processor", void 0);
21856
- __decorate$2([
21993
+ __decorate$3([
21857
21994
  HasMany({ through: "ad4m://interp/sources", datatype: "xsd:string" }),
21858
- __metadata$2("design:type", Array)
21995
+ __metadata$3("design:type", Array)
21859
21996
  ], InterpretationRun.prototype, "sources", void 0);
21860
- __decorate$2([
21997
+ __decorate$3([
21861
21998
  Optional({ through: "ad4m://interp/debug_prompt", resolveLanguage: "literal" }),
21862
- __metadata$2("design:type", String)
21999
+ __metadata$3("design:type", String)
21863
22000
  ], InterpretationRun.prototype, "debugPrompt", void 0);
21864
- __decorate$2([
22001
+ __decorate$3([
21865
22002
  Optional({ through: "ad4m://interp/debug_response", resolveLanguage: "literal" }),
21866
- __metadata$2("design:type", String)
22003
+ __metadata$3("design:type", String)
21867
22004
  ], InterpretationRun.prototype, "debugResponse", void 0);
21868
- InterpretationRun = __decorate$2([
22005
+ InterpretationRun = __decorate$3([
21869
22006
  Model$1({ name: "InterpretationRun" })
21870
22007
  ], InterpretationRun);
21871
22008
  // ── InterpretationOverlay ───────────────────────────────────────────────────
@@ -21895,15 +22032,15 @@ let InterpretationOverlay = class InterpretationOverlay extends Ad4mModel {
21895
22032
  this.kind = "";
21896
22033
  }
21897
22034
  };
21898
- __decorate$2([
22035
+ __decorate$3([
21899
22036
  Property({ through: "ad4m://interp/kind", required: true }),
21900
- __metadata$2("design:type", String)
22037
+ __metadata$3("design:type", String)
21901
22038
  ], InterpretationOverlay.prototype, "kind", void 0);
21902
- __decorate$2([
22039
+ __decorate$3([
21903
22040
  Optional({ through: "ad4m://interp/run" }),
21904
- __metadata$2("design:type", String)
22041
+ __metadata$3("design:type", String)
21905
22042
  ], InterpretationOverlay.prototype, "run", void 0);
21906
- InterpretationOverlay = __decorate$2([
22043
+ InterpretationOverlay = __decorate$3([
21907
22044
  Model$1({ name: "InterpretationOverlay" })
21908
22045
  ], InterpretationOverlay);
21909
22046
 
@@ -21927,13 +22064,13 @@ InterpretationOverlay = __decorate$2([
21927
22064
  * - the SDNA-parity test locks TS/Rust drift against
21928
22065
  * `rust-executor/src/perspectives/hardwired_sdna/flow_transition_proposal.json`.
21929
22066
  */
21930
- var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22067
+ var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
21931
22068
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
21932
22069
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21933
22070
  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;
21934
22071
  return c > 3 && r && Object.defineProperty(target, key, r), r;
21935
22072
  };
21936
- var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22073
+ var __metadata$2 = (undefined && undefined.__metadata) || function (k, v) {
21937
22074
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
21938
22075
  };
21939
22076
  /**
@@ -22040,55 +22177,55 @@ let FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel {
22040
22177
  // of the proposal's own links (all written together during create_subject).
22041
22178
  }
22042
22179
  };
22043
- __decorate$1([
22180
+ __decorate$2([
22044
22181
  Property({ through: "ad4m://flow/instance", required: true, identity: true }),
22045
- __metadata$1("design:type", String)
22182
+ __metadata$2("design:type", String)
22046
22183
  ], FlowTransitionProposal.prototype, "flowInstance", void 0);
22047
- __decorate$1([
22184
+ __decorate$2([
22048
22185
  Property({ through: "ad4m://flow/from_state", required: true }),
22049
- __metadata$1("design:type", String)
22186
+ __metadata$2("design:type", String)
22050
22187
  ], FlowTransitionProposal.prototype, "fromState", void 0);
22051
- __decorate$1([
22188
+ __decorate$2([
22052
22189
  Property({ through: "ad4m://flow/to_state", required: true }),
22053
- __metadata$1("design:type", String)
22190
+ __metadata$2("design:type", String)
22054
22191
  ], FlowTransitionProposal.prototype, "toState", void 0);
22055
- __decorate$1([
22192
+ __decorate$2([
22056
22193
  Property({ through: "ad4m://flow/proposer", required: true, getter: PROPOSER_GETTER, datatype: "xsd:string" }),
22057
- __metadata$1("design:type", String)
22194
+ __metadata$2("design:type", String)
22058
22195
  ], FlowTransitionProposal.prototype, "proposer", void 0);
22059
- __decorate$1([
22196
+ __decorate$2([
22060
22197
  HasMany({ through: "ad4m://flow/evidence", datatype: "xsd:string" }),
22061
- __metadata$1("design:type", Array)
22198
+ __metadata$2("design:type", Array)
22062
22199
  ], FlowTransitionProposal.prototype, "evidence", void 0);
22063
- __decorate$1([
22200
+ __decorate$2([
22064
22201
  Property({ through: "ad4m://flow/evidence_hashes", required: true }),
22065
- __metadata$1("design:type", String)
22202
+ __metadata$2("design:type", String)
22066
22203
  ], FlowTransitionProposal.prototype, "evidenceHashes", void 0);
22067
- __decorate$1([
22204
+ __decorate$2([
22068
22205
  HasMany({ through: "ad4m://flow/output", datatype: "xsd:string" }),
22069
- __metadata$1("design:type", Array)
22206
+ __metadata$2("design:type", Array)
22070
22207
  ], FlowTransitionProposal.prototype, "outputs", void 0);
22071
- __decorate$1([
22208
+ __decorate$2([
22072
22209
  Property({ through: "ad4m://flow/outputs_hash" }),
22073
- __metadata$1("design:type", String)
22210
+ __metadata$2("design:type", String)
22074
22211
  ], FlowTransitionProposal.prototype, "outputsHash", void 0);
22075
- __decorate$1([
22212
+ __decorate$2([
22076
22213
  Property({ through: "ad4m://flow/nonce" }),
22077
- __metadata$1("design:type", String)
22214
+ __metadata$2("design:type", String)
22078
22215
  ], FlowTransitionProposal.prototype, "nonce", void 0);
22079
- __decorate$1([
22216
+ __decorate$2([
22080
22217
  Optional({ through: "ad4m://flow/run_uri" }),
22081
- __metadata$1("design:type", String)
22218
+ __metadata$2("design:type", String)
22082
22219
  ], FlowTransitionProposal.prototype, "runUri", void 0);
22083
- __decorate$1([
22220
+ __decorate$2([
22084
22221
  Optional({ through: "ad4m://flow/rationale" }),
22085
- __metadata$1("design:type", String)
22222
+ __metadata$2("design:type", String)
22086
22223
  ], FlowTransitionProposal.prototype, "rationale", void 0);
22087
- __decorate$1([
22224
+ __decorate$2([
22088
22225
  HasMany({ through: "ad4m://acceptedBy", getter: ACCEPTED_BY_GETTER, readOnly: true }),
22089
- __metadata$1("design:type", Array)
22226
+ __metadata$2("design:type", Array)
22090
22227
  ], FlowTransitionProposal.prototype, "acceptedBy", void 0);
22091
- FlowTransitionProposal = __decorate$1([
22228
+ FlowTransitionProposal = __decorate$2([
22092
22229
  Model$1({ name: "FlowTransitionProposal" })
22093
22230
  ], FlowTransitionProposal);
22094
22231
  // ── FlowInstanceRecord ──────────────────────────────────────────────────────
@@ -22148,25 +22285,25 @@ let FlowInstanceRecord = class FlowInstanceRecord extends Ad4mModel {
22148
22285
  // of the instance's own links (all written together during `mint_flow_instance`).
22149
22286
  }
22150
22287
  };
22151
- __decorate$1([
22288
+ __decorate$2([
22152
22289
  Property({ through: "ad4m://flow/flow_uri", required: true, identity: true }),
22153
- __metadata$1("design:type", String)
22290
+ __metadata$2("design:type", String)
22154
22291
  ], FlowInstanceRecord.prototype, "flowUri", void 0);
22155
- __decorate$1([
22292
+ __decorate$2([
22156
22293
  Property({ through: "ad4m://flow/base", required: true }),
22157
- __metadata$1("design:type", String)
22294
+ __metadata$2("design:type", String)
22158
22295
  ], FlowInstanceRecord.prototype, "subject", void 0);
22159
- FlowInstanceRecord = __decorate$1([
22296
+ FlowInstanceRecord = __decorate$2([
22160
22297
  Model$1({ name: "FlowInstance" })
22161
22298
  ], FlowInstanceRecord);
22162
22299
 
22163
- var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22300
+ var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22164
22301
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22165
22302
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22166
22303
  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;
22167
22304
  return c > 3 && r && Object.defineProperty(target, key, r), r;
22168
22305
  };
22169
- var __metadata = (undefined && undefined.__metadata) || function (k, v) {
22306
+ var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22170
22307
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22171
22308
  };
22172
22309
  /**
@@ -22202,14 +22339,74 @@ let TextContent = class TextContent extends Ad4mModel {
22202
22339
  };
22203
22340
  /** The URI the executor reads it by. */
22204
22341
  TextContent.builtinUri = "ad4m://TextContent";
22205
- __decorate([
22342
+ __decorate$1([
22206
22343
  Property({ through: "ad4m://text" }),
22207
- __metadata("design:type", String)
22344
+ __metadata$1("design:type", String)
22208
22345
  ], TextContent.prototype, "text", void 0);
22209
- TextContent = __decorate([
22346
+ TextContent = __decorate$1([
22210
22347
  Model$1({ name: "TextContent", abstract: true })
22211
22348
  ], TextContent);
22212
22349
 
22350
+ var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22351
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22352
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22353
+ 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;
22354
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
22355
+ };
22356
+ var __metadata = (undefined && undefined.__metadata) || function (k, v) {
22357
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22358
+ };
22359
+ /**
22360
+ * The built-in abstract class `Container { children }` (#1446): what holds
22361
+ * other records — a channel, a thread, a post, a call, a document, a board.
22362
+ *
22363
+ * X is contained in P when `P ad4m://has_child X` exists, whatever P is (an
22364
+ * instance of any class, or a node no class describes, such as
22365
+ * `ad4m://self`), or when P is an instance of a class whose `children`
22366
+ * relation (by name, or aliased to `children`) links X:
22367
+ *
22368
+ * ```typescript
22369
+ * @Model({ name: "Block", implements: [Container] })
22370
+ * class Block extends Ad4mModel {
22371
+ * @HasMany({ through: "we://child", alias: { Container: "children" } })
22372
+ * blocks: string[] = [];
22373
+ * }
22374
+ *
22375
+ * // Messages held by P, through has_child or a Block's we://child:
22376
+ * await Message.findAll(perspective, { parent: { id: P } });
22377
+ * // Everything that holds X:
22378
+ * await Container.findAll(perspective, { parent: { ids: [X], direction: "in" } });
22379
+ * ```
22380
+ *
22381
+ * A row's `children` is everything it holds, merged across its classes. A
22382
+ * node no class describes is a row of its own when it holds something by
22383
+ * `has_child`. Always scope a `Container` query (`where: { id }`, a
22384
+ * `children` filter or `parent`): unscoped, it reads every holder in the
22385
+ * perspective.
22386
+ *
22387
+ * Built in: the executor declares it (mirrors
22388
+ * `rust-executor/src/perspectives/hardwired_sdna/container.json`) and reads
22389
+ * it by its URI, `ad4m://Container`, so a perspective never stores it and an
22390
+ * app class named `Container` does not replace it. `register()` on it writes
22391
+ * nothing.
22392
+ */
22393
+ let Container = class Container extends Ad4mModel {
22394
+ constructor() {
22395
+ super(...arguments);
22396
+ /** What it holds, whatever their class. */
22397
+ this.children = [];
22398
+ }
22399
+ };
22400
+ /** The URI the executor reads it by. */
22401
+ Container.builtinUri = "ad4m://Container";
22402
+ __decorate([
22403
+ HasMany({ through: "ad4m://has_child" }),
22404
+ __metadata("design:type", Array)
22405
+ ], Container.prototype, "children", void 0);
22406
+ Container = __decorate([
22407
+ Model$1({ name: "Container", abstract: true })
22408
+ ], Container);
22409
+
22213
22410
  /**
22214
22411
  * `FlowInstance` — object-oriented wrapper for a running flow.
22215
22412
  *
@@ -22798,6 +22995,107 @@ function parseLitBoolean(val) {
22798
22995
  * module (`plugins/ad4m/wakerSubscriptionManager.ts`) rather than carrying its
22799
22996
  * own copy. Any behaviour change belongs here.
22800
22997
  */
22998
+ /** A letter, combining mark, digit or underscore: what a term must not touch. */
22999
+ const WORD_CHAR = "[\\p{L}\\p{M}\\p{N}_]";
23000
+ /**
23001
+ * The elements a message's HTML is made of. A `<` before any other name is text:
23002
+ * We stores plain text, where "<hey Data> can you look" is words.
23003
+ */
23004
+ const ELEMENT = "a|abbr|b|bdi|bdo|blockquote|br|caption|center|cite|code|col|colgroup|dd|del|details|dfn|div|dl|dt|em|" +
23005
+ "figcaption|figure|font|h[1-6]|hr|i|img|ins|kbd|label|li|mark|ol|p|pre|q|s|samp|section|article|small|" +
23006
+ "span|strike|strong|sub|summary|sup|table|tbody|td|tfoot|th|thead|time|tr|u|ul|var|wbr|script|style";
23007
+ /** An attribute: a name, then optionally `=` and a quoted value (which may hold `>`) or an unquoted one. */
23008
+ const ATTRIBUTE = `\\s+[A-Za-z_:][-\\w:.]*(?:\\s*=\\s*(?:"[^"]*"|'[^']*'|[^\\s"'=<>\`]+))?`;
23009
+ /**
23010
+ * Markup: a comment, a `<script>`/`<style>` element with its contents, or a tag of
23011
+ * a known element whose rest is a valid attribute list. "a < b" and
23012
+ * "if a <b then ask Data, else c -> d" are text: the comma is no attribute.
23013
+ */
23014
+ const TAG = new RegExp(`<!--[\\s\\S]*?-->` +
23015
+ `|<(script|style)(?=[\\s/>])(?:${ATTRIBUTE})*\\s*>[\\s\\S]*?<\\/\\1\\s*>` +
23016
+ `|<(?:${ELEMENT})(?=[\\s/>])(?:${ATTRIBUTE})*\\s*\\/?>` +
23017
+ `|<\\/(?:${ELEMENT})\\s*>`, "gi");
23018
+ /** Tags that break a line: replaced by a space, so `<p>hi</p><p>Data</p>` keeps "Data" a word. */
23019
+ const BREAKING_TAG = /^<\/?(?:p|div|br|hr|li|ul|ol|h[1-6]|blockquote|pre|tr|td|th|table|section|article)\b/i;
23020
+ /**
23021
+ * The attributes a mention puts its target's DID in: Flux's `<a data-type="mention"
23022
+ * href="did:…">`, older Flux messages' `<span data-id="did:…">`, and We's editor chip
23023
+ * `<span class="we-mention" data-did="did:…">`.
23024
+ */
23025
+ const ATTRIBUTES = new RegExp(ATTRIBUTE, "g");
23026
+ const MENTION_TARGET = /^\s+(?:href|data-id|data-did)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))$/i;
23027
+ /**
23028
+ * How much of a record's text the word check reads. Dropping markup costs time
23029
+ * quadratic in a run of unclosed `<script>`, `<style>` or `<!--` openers, so a
23030
+ * very long text could hold the event loop for seconds, and a row that holds
23031
+ * no term is checked again on every result while it is in the window. A term
23032
+ * past this many characters does not wake.
23033
+ */
23034
+ const MENTION_TEXT_LIMIT = 16384;
23035
+ const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
23036
+ function decodeEntities(s) {
23037
+ return s.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi, (whole, ref) => {
23038
+ if (ref[0] !== "#")
23039
+ return ENTITIES[ref.toLowerCase()] ?? whole;
23040
+ const code = ref[1] === "x" || ref[1] === "X" ? parseInt(ref.slice(2), 16) : parseInt(ref.slice(1), 10);
23041
+ return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : whole;
23042
+ });
23043
+ }
23044
+ /**
23045
+ * What a reader sees of `text`, and the DIDs its mentions point at. `text` may be
23046
+ * HTML (TextContent allows it): tag names and attributes are markup, not words, so
23047
+ * a bot named "Data" must not wake on `data-type="mention"` in a mention of
23048
+ * someone else. Plain text passes through unchanged, apart from entities.
23049
+ */
23050
+ function readableParts(text) {
23051
+ const targets = [];
23052
+ const visible = text.replace(TAG, (tag, scriptOrStyle) => {
23053
+ if (scriptOrStyle)
23054
+ return " ";
23055
+ if (tag.startsWith("<!--"))
23056
+ return "";
23057
+ // Parse complete attributes first: a DID-shaped string inside `title`
23058
+ // is not a target attribute and must not wake an agent.
23059
+ for (const attribute of tag.matchAll(ATTRIBUTES)) {
23060
+ const target = MENTION_TARGET.exec(attribute[0]);
23061
+ if (target)
23062
+ targets.push(decodeEntities(target[1] ?? target[2] ?? target[3]));
23063
+ }
23064
+ return BREAKING_TAG.test(tag) ? " " : "";
23065
+ });
23066
+ return { visible: decodeEntities(visible), targets };
23067
+ }
23068
+ /**
23069
+ * Whether `text` holds one of `terms` as a whole word, case-insensitively:
23070
+ * "Data" is in "hi Data!", "@data" and "Data's turn", not in "metadata" or
23071
+ * "database". A term is matched literally (regex characters, quotes) and must
23072
+ * not touch a letter, mark, digit or underscore on either side, so a name
23073
+ * that starts or ends with punctuation still matches. Same rule as #1459's
23074
+ * SPARQL `(?:^|\W)term(?:\W|$)`.
23075
+ *
23076
+ * The rule runs on the visible text only: in HTML, tags and attributes are
23077
+ * dropped and entities decoded first. A mention's target attribute
23078
+ * (`href`, `data-id`, `data-did`) matches an exact, case-sensitive DID term, which
23079
+ * is how a mention by DID is found when the DID is not in the visible text.
23080
+ *
23081
+ * The mention query's `contains` matches substrings (model query has no word
23082
+ * match); this is the check that keeps "data" from waking on "metadata".
23083
+ * It reads the first {@link MENTION_TEXT_LIMIT} characters only.
23084
+ */
23085
+ function holdsAWholeWordTerm(text, terms) {
23086
+ const { visible, targets } = readableParts(text.slice(0, MENTION_TEXT_LIMIT));
23087
+ return terms.some((term) => {
23088
+ if (!term)
23089
+ return false;
23090
+ if (term.startsWith("did:") && targets.includes(term))
23091
+ return true;
23092
+ const escaped = term.replace(/[\\^$.*+?()[\]{}|\/]/g, "\\$&");
23093
+ return new RegExp(`(?<!${WORD_CHAR})${escaped}(?!${WORD_CHAR})`, "iu").test(visible);
23094
+ });
23095
+ }
23096
+ /** The built-in `Container` (`Container.builtinUri`; not imported, so the
23097
+ * plugin bundle does not pull in the model layer). */
23098
+ const CONTAINER = "ad4m://Container";
22801
23099
  /**
22802
23100
  * Add a short cause hint to known subscription failures.
22803
23101
  * The executor needs its main key to register a live query; on a restarted
@@ -22807,13 +23105,13 @@ function hintFor(msg) {
22807
23105
  // "Executor is locked" is the current executor's message; "main key not
22808
23106
  // found" is what older executors (and unrelated key lookups) say for the
22809
23107
  // same locked state. Either way the caller cannot fix it themselves: keys
22810
- // live in memory only, so every restart locks the node again and only its
23108
+ // live in memory only, so every restart locks the executor again and only its
22811
23109
  // operator can unlock it.
22812
23110
  if (/executor is locked/i.test(msg) || /main key not found/i.test(msg)) {
22813
- return " — the executor is locked (its keys live in memory only, so every restart locks it again). Only the node's operator can unlock it: contact them and ask for unlockAgent, then subscribe again — a pending subscription re-attempts on its own once the node is unlocked";
23111
+ return " — the executor is locked (its keys live in memory only, so every restart locks it again). Only the executor's operator can unlock it: contact them and ask for unlockAgent, then subscribe again — a pending subscription re-attempts on its own once the executor is unlocked";
22814
23112
  }
22815
23113
  if (/timed out after \d+ms/i.test(msg)) {
22816
- return " — the executor accepted the waker's connection but never answered; check that the waker is pointed at the right executor host and API port (executorUrl in the plugin config) and that the node is unlocked";
23114
+ return " — the executor accepted the waker's connection but never answered; check that the waker is pointed at the right executor host and API port (executorUrl in the plugin config) and that the executor is unlocked";
22817
23115
  }
22818
23116
  return "";
22819
23117
  }
@@ -22864,6 +23162,20 @@ class WakerSubscriptionManager {
22864
23162
  /** Per-subscription set of already-processed message addresses (for mention subs)
22865
23163
  * or serialized result hash (for channel-messages subs). */
22866
23164
  this.seenMessages = new Map();
23165
+ /**
23166
+ * Per mention subscription: the addresses whose wake was delivered, or that were history when
23167
+ * the subscription opened. This, not `seenMessages`, is what gets persisted: an address joins
23168
+ * `seenMessages` as soon as it is read, while its parents are still resolving and before any
23169
+ * wake, so a restart in between must not take it as done.
23170
+ */
23171
+ this.delivered = new Map();
23172
+ /**
23173
+ * Per mention subscription: mentions read but whose wake has not been delivered yet, keyed by
23174
+ * address. They accumulate across a debounce window, so one wake names all of them.
23175
+ */
23176
+ this.undelivered = new Map();
23177
+ /** Failed wake attempts in a row per subscription, for the retry backoff. */
23178
+ this.wakeFailures = new Map();
22867
23179
  this.perspectiveClient = options.perspectiveClient;
22868
23180
  this.logger = options.logger;
22869
23181
  this.debounceMs = options.debounceMs ?? 2000;
@@ -22874,6 +23186,7 @@ class WakerSubscriptionManager {
22874
23186
  this.previousSeenMessages = options.previousSeenMessages ?? {};
22875
23187
  this.retryPendingMs = options.retryPendingMs ?? 30000;
22876
23188
  this.subscribeTimeoutMs = options.subscribeTimeoutMs ?? 15000;
23189
+ this.retryWakeMs = options.retryWakeMs ?? 5000;
22877
23190
  }
22878
23191
  /** A token identifying this attempt at subscribing `id`. */
22879
23192
  beginAttempt(id) {
@@ -22886,7 +23199,7 @@ class WakerSubscriptionManager {
22886
23199
  return token.epoch !== this.epoch || this.generations.get(id) !== token.gen;
22887
23200
  }
22888
23201
  /**
22889
- * Create a live SPARQL subscription.
23202
+ * Create a live subscription: SPARQL, or a model query when `sub.className` is set.
22890
23203
  * If a subscription with the same id already exists, it is disposed first.
22891
23204
  */
22892
23205
  async subscribe(sub) {
@@ -22897,9 +23210,16 @@ class WakerSubscriptionManager {
22897
23210
  throw new Error("WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options");
22898
23211
  }
22899
23212
  const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;
23213
+ if (sub.type === "mention" && sub.className && !sub.terms?.length) {
23214
+ // Without terms the whole-word check cannot run, and every substring
23215
+ // ("metadata" for "data") would wake the agent.
23216
+ throw new Error(`Waker subscription ${sub.id}: a mention subscription needs its terms (get_mention_waker_config returns them)`);
23217
+ }
22900
23218
  this.logger.info(`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`);
22901
- this.logger.info(`[waker] ${sub.id}: SPARQL query:\n${sub.query}`);
22902
- const proxy = new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
23219
+ this.logger.info(`[waker] ${sub.id}: ${sub.className ? `model query over ${sub.className}` : "SPARQL query"}:\n${sub.query}`);
23220
+ const proxy = sub.className
23221
+ ? new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient, sub.className)
23222
+ : new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
22903
23223
  // Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
22904
23224
  // rejects this promise internally when subscribe() fails, and if nobody catches
22905
23225
  // it before the next microtask it crashes the process.
@@ -22940,6 +23260,7 @@ class WakerSubscriptionManager {
22940
23260
  // reported as active or persisted as if it were.
22941
23261
  this.activeSubscriptions.delete(sub.id);
22942
23262
  this.seenMessages.delete(sub.id);
23263
+ this.delivered.delete(sub.id);
22943
23264
  this.persist();
22944
23265
  // Keep it pending and re-attempt: the usual cause (locked wallet, executor
22945
23266
  // mid-restart, a handshake the executor never answered) clears on its
@@ -22964,33 +23285,62 @@ class WakerSubscriptionManager {
22964
23285
  this.pendingSubscriptions.delete(sub.id);
22965
23286
  this.logger.info(`[waker] ${sub.id}: subscription initialized successfully`);
22966
23287
  // Seed from persisted seen messages so we don't re-wake after restart
23288
+ const restored = Object.prototype.hasOwnProperty.call(this.previousSeenMessages, sub.id);
22967
23289
  const seen = new Set(this.previousSeenMessages[sub.id] ?? []);
22968
23290
  this.seenMessages.set(sub.id, seen);
23291
+ this.delivered.set(sub.id, new Set(seen));
22969
23292
  if (seen.size > 0) {
22970
23293
  this.logger.info(`[waker] ${sub.id}: seeded ${seen.size} seen message(s) from persisted state`);
22971
23294
  }
22972
- proxy.onResult(async (result) => {
22973
- this.logger.info(`[waker] ${sub.id}: onResult fired — type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);
22974
- // Query engine can deliver non-array values (e.g. false) on disconnect/reconnect — ignore them
22975
- if (!Array.isArray(result)) {
22976
- this.logger.warn(`[waker] ${sub.id}: ignoring non-array result: ${JSON.stringify(result)}`);
23295
+ // `opening` is the result the subscription holds when it opens (`proxy.result`): `onResult`
23296
+ // only reports later changes, so this is the one chance to see what was written meanwhile.
23297
+ const handleResult = async (result, opening = false) => {
23298
+ this.logger.info(`[waker] ${sub.id}: ${opening ? "opening result" : "onResult fired"} — type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);
23299
+ // A model subscription delivers `{ instances }`, SPARQL an array of
23300
+ // rows. Anything else (e.g. `false` on a disconnect/reconnect) is
23301
+ // ignored.
23302
+ const rows = sub.className ? result?.instances : result;
23303
+ if (!Array.isArray(rows)) {
23304
+ this.logger.warn(`[waker] ${sub.id}: ignoring result without ${sub.className ? "instances" : "rows"}: ${JSON.stringify(result)}`);
22977
23305
  return;
22978
23306
  }
22979
23307
  if (sub.type === "mention") {
22980
- // For mention subscriptions: track seen message addresses.
22981
- // Only wake for messages we haven't seen before.
23308
+ // For mention subscriptions: track seen record ids.
23309
+ // Only wake for records we haven't seen before.
22982
23310
  const currentSeen = this.seenMessages.get(sub.id) ?? new Set();
22983
23311
  const newMessages = [];
22984
- for (const item of result) {
22985
- if (item && item.source && !currentSeen.has(item.source)) {
22986
- newMessages.push(item.source);
23312
+ const terms = sub.terms ?? [];
23313
+ for (const item of rows) {
23314
+ // A SPARQL row names the record as `source`, a model row as `id`.
23315
+ const address = sub.className ? item?.id : item?.source;
23316
+ if (typeof address !== "string" || !address || currentSeen.has(address))
23317
+ continue;
23318
+ if (terms.length) {
23319
+ // The mention query matched a substring; wake only on a whole word.
23320
+ const text = Array.isArray(item.text) ? item.text.join(" ") : item.text;
23321
+ if (typeof text !== "string" || !holdsAWholeWordTerm(text, terms)) {
23322
+ this.logger.debug(`[waker] ${sub.id}: ${address} holds no term as a whole word, skipping`);
23323
+ continue;
23324
+ }
22987
23325
  }
23326
+ currentSeen.add(address);
23327
+ newMessages.push(address);
22988
23328
  }
22989
23329
  if (newMessages.length === 0) {
22990
- this.logger.info(`[waker] ${sub.id}: all ${result.length} items already seen, skipping`);
23330
+ this.logger.info(`[waker] ${sub.id}: no new mention among ${rows.length} items, skipping`);
23331
+ return;
23332
+ }
23333
+ if (opening && !restored) {
23334
+ // A new subscription: what it opens on is history, readable on demand, not news.
23335
+ this.seenMessages.set(sub.id, currentSeen);
23336
+ const done = this.delivered.get(sub.id) ?? new Set();
23337
+ for (const address of newMessages)
23338
+ done.add(address);
23339
+ this.delivered.set(sub.id, done);
23340
+ this.logger.info(`[waker] ${sub.id}: ${newMessages.length} existing mention(s) taken as history, not woken`);
22991
23341
  return;
22992
23342
  }
22993
- this.logger.info(`[waker] ${sub.id}: ${newMessages.length} new message(s) out of ${result.length} total`);
23343
+ this.logger.info(`[waker] ${sub.id}: ${newMessages.length} new message(s) out of ${rows.length} total`);
22994
23344
  // Resolve parents, and the chain above them, per new message
22995
23345
  const mentions = [];
22996
23346
  for (const msgAddr of newMessages) {
@@ -23001,25 +23351,20 @@ class WakerSubscriptionManager {
23001
23351
  (ancestors.length ? `; ancestors: ${ancestors.join(", ")}` : ""));
23002
23352
  mentions.push({ address: msgAddr, parents, ancestors });
23003
23353
  }
23004
- // Mark all new messages as seen
23005
- for (const addr of newMessages) {
23006
- currentSeen.add(addr);
23007
- }
23008
23354
  this.seenMessages.set(sub.id, currentSeen);
23009
- // Debounce the wake callback
23010
- const existing = this.debounceTimers.get(sub.id);
23011
- if (existing)
23012
- clearTimeout(existing);
23013
- this.debounceTimers.set(sub.id, setTimeout(() => {
23014
- this.onWake(sub, result, mentions);
23015
- this.debounceTimers.delete(sub.id);
23016
- this.persist();
23017
- }, this.debounceMs));
23355
+ const pending = this.undelivered.get(sub.id) ?? new Map();
23356
+ for (const mention of mentions)
23357
+ pending.set(mention.address, mention);
23358
+ this.undelivered.set(sub.id, pending);
23359
+ this.scheduleMentionWake(sub, result, this.debounceMs);
23018
23360
  }
23019
23361
  else {
23362
+ // A container's contents when the subscription opens are not an update.
23363
+ if (opening)
23364
+ return;
23020
23365
  // For channel-messages: always notify the agent on every subscription push.
23021
23366
  // No deduplication — the agent reads recent messages itself.
23022
- this.logger.info(`[waker] ${sub.id}: channel update (${result.length} items)`);
23367
+ this.logger.info(`[waker] ${sub.id}: channel update (${rows.length} items)`);
23023
23368
  const existing = this.debounceTimers.get(sub.id);
23024
23369
  if (existing)
23025
23370
  clearTimeout(existing);
@@ -23028,7 +23373,8 @@ class WakerSubscriptionManager {
23028
23373
  this.debounceTimers.delete(sub.id);
23029
23374
  }, this.debounceMs));
23030
23375
  }
23031
- });
23376
+ };
23377
+ proxy.onResult((result) => handleResult(result));
23032
23378
  if (this.isStale(sub.id, token)) {
23033
23379
  try {
23034
23380
  proxy.dispose();
@@ -23038,6 +23384,16 @@ class WakerSubscriptionManager {
23038
23384
  }
23039
23385
  this.proxies.set(sub.id, proxy);
23040
23386
  this.activeSubscriptions.set(sub.id, sub);
23387
+ // After a restart this wakes on mentions written while the waker was down; on a new
23388
+ // subscription it records the existing ones as history.
23389
+ if (proxy.result !== undefined) {
23390
+ try {
23391
+ await handleResult(proxy.result, true);
23392
+ }
23393
+ catch (e) {
23394
+ this.logger.warn(`[waker] ${sub.id}: reading the opening result failed: ${e?.message ?? e}`);
23395
+ }
23396
+ }
23041
23397
  this.persist();
23042
23398
  this.logger.info(`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`);
23043
23399
  }
@@ -23113,9 +23469,61 @@ class WakerSubscriptionManager {
23113
23469
  this.activeSubscriptions.delete(id);
23114
23470
  this.pendingSubscriptions.delete(id);
23115
23471
  this.seenMessages.delete(id);
23472
+ this.delivered.delete(id);
23473
+ this.undelivered.delete(id);
23474
+ this.wakeFailures.delete(id);
23116
23475
  if (persist)
23117
23476
  this.persist();
23118
23477
  }
23478
+ /** (Re)start the timer that offers `sub`'s undelivered mentions to `onWake` after `delayMs`. */
23479
+ scheduleMentionWake(sub, result, delayMs) {
23480
+ const existing = this.debounceTimers.get(sub.id);
23481
+ if (existing)
23482
+ clearTimeout(existing);
23483
+ this.debounceTimers.set(sub.id, setTimeout(() => {
23484
+ this.debounceTimers.delete(sub.id);
23485
+ void this.deliverMentions(sub, result);
23486
+ }, delayMs));
23487
+ }
23488
+ /**
23489
+ * Offer every undelivered mention of `sub` in one wake. On delivery they join the persisted
23490
+ * seen set; on failure they stay undelivered and are offered again with backoff.
23491
+ */
23492
+ async deliverMentions(sub, result) {
23493
+ const pending = this.undelivered.get(sub.id);
23494
+ if (!pending?.size || !this.activeSubscriptions.has(sub.id))
23495
+ return;
23496
+ const mentions = Array.from(pending.values());
23497
+ let delivered;
23498
+ try {
23499
+ delivered = (await this.onWake(sub, result, mentions)) !== false;
23500
+ }
23501
+ catch (e) {
23502
+ this.logger.warn(`[waker] ${sub.id}: wake callback threw: ${e?.message ?? e}`);
23503
+ delivered = false;
23504
+ }
23505
+ // Disposed while the wake was in flight: nothing left to retry or persist.
23506
+ if (this.undelivered.get(sub.id) !== pending)
23507
+ return;
23508
+ if (!delivered) {
23509
+ const failures = (this.wakeFailures.get(sub.id) ?? 0) + 1;
23510
+ this.wakeFailures.set(sub.id, failures);
23511
+ const delay = Math.min(this.retryWakeMs * 2 ** (failures - 1), 60000);
23512
+ this.logger.warn(`[waker] ${sub.id}: wake for ${mentions.length} mention(s) not delivered, offering again in ${delay}ms`);
23513
+ // A newer result arriving meanwhile restarts the timer and joins this wake.
23514
+ if (!this.debounceTimers.has(sub.id))
23515
+ this.scheduleMentionWake(sub, result, delay);
23516
+ return;
23517
+ }
23518
+ this.wakeFailures.delete(sub.id);
23519
+ const done = this.delivered.get(sub.id) ?? new Set();
23520
+ for (const mention of mentions) {
23521
+ pending.delete(mention.address);
23522
+ done.add(mention.address);
23523
+ }
23524
+ this.delivered.set(sub.id, done);
23525
+ this.persist();
23526
+ }
23119
23527
  /** Dispose all active subscriptions and drop anything still pending. */
23120
23528
  disposeAll() {
23121
23529
  // Bump the epoch first: in-flight subscribe() calls have no proxy in the
@@ -23138,60 +23546,50 @@ class WakerSubscriptionManager {
23138
23546
  has(id) {
23139
23547
  return this.activeSubscriptions.has(id);
23140
23548
  }
23141
- /** Resolve one containment level in one query; skip unsafe IRI tokens and treat failures as none. */
23549
+ /**
23550
+ * Everything holding any of `addresses`, in one model query: a `Container`
23551
+ * step in (#1446). The executor follows `ad4m://has_child` on any node and
23552
+ * each class's own `children` relation on its instances, so the waker
23553
+ * looks up no predicate. Failures count as none.
23554
+ */
23142
23555
  async parentsOf(sub, addresses) {
23143
- const safe = [...new Set(addresses)].filter((address) => {
23144
- if (/[<>"{}|^`\\\s\x00-\x20]/.test(address)) {
23145
- this.logger.warn(`[waker] ${sub.id}: skipping parent lookup for unsafe address ${JSON.stringify(address)}`);
23146
- return false;
23147
- }
23148
- return true;
23149
- });
23150
- if (!safe.length)
23556
+ if (!addresses.length)
23151
23557
  return [];
23152
- try {
23153
- const query = safe.length === 1
23154
- ? `SELECT ?source WHERE { ?source <ad4m://has_child> <${safe[0]}> . }`
23155
- : `SELECT ?source WHERE { VALUES ?child { ${safe.map((address) => `<${address}>`).join(" ")} } ?source <ad4m://has_child> ?child . }`;
23156
- const rows = await this.perspectiveClient.querySparql(sub.perspective, query);
23157
- if (!Array.isArray(rows))
23158
- return [];
23159
- // A row omits a variable left unbound in its solution.
23160
- return rows.map((row) => row?.source).filter((source) => typeof source === "string");
23161
- }
23162
- catch (err) {
23163
- this.logger.warn(`[waker] ${sub.id}: parent resolution failed for ${JSON.stringify(safe)} — ${err?.message ?? err}`);
23164
- return [];
23165
- }
23558
+ return this.containers(sub, { ids: [...new Set(addresses)], direction: "in" }, addresses);
23166
23559
  }
23167
23560
  /**
23168
- * The chain above an item's parents, a level at a time, nearest first, up to `ancestorDepth`.
23169
- *
23170
- * Breadth-first with a visited set: containment is a graph, not a tree — an item can sit in two
23171
- * places, and nothing stops a cycle — so each address is reported once and the walk always ends.
23172
- * Each level uses one batched parent lookup, bounded by the depth.
23561
+ * The chain above an item's parents, nearest first, up to `ancestorDepth` levels: one
23562
+ * transitive `Container` walk in from the parents, bounded by `maxDepth`. The executor walks
23563
+ * containment as a graph, so each address comes once however many paths reach it, and a
23564
+ * cycle ends. The item and its parents are never reported as ancestors.
23173
23565
  */
23174
23566
  async ancestorsOf(sub, address, parents) {
23567
+ if (!parents.length || this.ancestorDepth <= 0)
23568
+ return [];
23569
+ const scope = { ids: parents, direction: "in", transitive: true, maxDepth: this.ancestorDepth };
23175
23570
  const seen = new Set([address, ...parents]);
23176
- const ancestors = [];
23177
- let level = parents;
23178
- for (let depth = 0; depth < this.ancestorDepth && level.length; depth++) {
23179
- const next = [];
23180
- for (const parent of await this.parentsOf(sub, level)) {
23181
- if (seen.has(parent))
23182
- continue;
23183
- seen.add(parent);
23184
- next.push(parent);
23185
- }
23186
- ancestors.push(...next);
23187
- level = next;
23571
+ return (await this.containers(sub, scope, parents)).filter((id) => !seen.has(id));
23572
+ }
23573
+ /** The ids of the `Container` rows `parent` scopes to, in the executor's order. */
23574
+ async containers(sub, parent, from) {
23575
+ try {
23576
+ const query = JSON.stringify({ parent, properties: [] });
23577
+ const result = await this.perspectiveClient.modelQuery(sub.perspective, CONTAINER, query);
23578
+ const instances = result?.instances;
23579
+ if (!Array.isArray(instances))
23580
+ return [];
23581
+ return instances.map((row) => row?.id).filter((id) => typeof id === "string");
23582
+ }
23583
+ catch (err) {
23584
+ this.logger.warn(`[waker] ${sub.id}: containment lookup failed for ${JSON.stringify(from)} — ${err?.message ?? err}`);
23585
+ return [];
23188
23586
  }
23189
- return ancestors;
23190
23587
  }
23191
23588
  persist() {
23192
23589
  if (this.onPersist) {
23193
23590
  const seen = {};
23194
- for (const [id, set] of this.seenMessages) {
23591
+ // Only what was delivered: anything else must wake again after a restart.
23592
+ for (const [id, set] of this.delivered) {
23195
23593
  seen[id] = Array.from(set);
23196
23594
  }
23197
23595
  this.onPersist(this.getActive(), seen);
@@ -23639,4 +24037,4 @@ const SCOPED_EVENTS = new Set([
23639
24037
  "flow-state-changed",
23640
24038
  ]);
23641
24039
 
23642
- export { ACCEPTED_BY_GETTER, AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, AutoProcessorConfig, BelongsToMany, BelongsToOne, CALL_PROTOCOL_VERSION, Capability, CapabilityInput, ComputeLogEntry, DEFAULT_ICE_SERVERS, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, FlowInstance, FlowInstanceRecord, FlowTransitionProposal, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, InterpretationOverlay, InterpretationRun, LONG_METHODS, LONG_TIMEOUT_MS, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LiveQuery, LocalModel, LocalModelInput, MeshManager, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PROPOSER_GETTER, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, READ_METHODS, ReadOnly, Resource, ResourceInput, RpcError, RuntimeInfo, SCOPED_EVENTS, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TextContent, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, applyUpdate, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, createTelepresenceChannel, determineNamespace, determinePredicate, effectiveLiteralStorage, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, hintFor, ifExpr, invalidatePerspectiveCache, isArrayType, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, isTraverseScope, linkEqual, linkExpressionInputToWire, linkExpressionToWire, linkMutationsToWire, literal, looksLikeUri, neighbourhoodExpressionFromWire, normalizeNamespaceString, normalizeSchemaType, normalizeValue, normalizeWhereForSparql, parseCallMessage, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, requireSingleParent, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString, valueToLiteralIri };
24040
+ export { ACCEPTED_BY_GETTER, AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, AutoProcessorConfig, BelongsToMany, BelongsToOne, CALL_PROTOCOL_VERSION, Capability, CapabilityInput, ComputeLogEntry, Container, DEFAULT_ICE_SERVERS, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, FlowInstance, FlowInstanceRecord, FlowTransitionProposal, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, InterpretationOverlay, InterpretationRun, LONG_METHODS, LONG_TIMEOUT_MS, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LiveQuery, LocalModel, LocalModelInput, MENTION_TEXT_LIMIT, MeshManager, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PROPOSER_GETTER, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, READ_METHODS, ReadOnly, Resource, ResourceInput, RpcError, RuntimeInfo, SCOPED_EVENTS, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TextContent, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, applyUpdate, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, createTelepresenceChannel, determineNamespace, determinePredicate, effectiveLiteralStorage, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, hintFor, holdsAWholeWordTerm, ifExpr, invalidatePerspectiveCache, isArrayType, isContainedScope, isContainmentTraversal, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, isTraverseScope, linkEqual, linkExpressionInputToWire, linkExpressionToWire, linkMutationsToWire, literal, looksLikeUri, neighbourhoodExpressionFromWire, normalizeNamespaceString, normalizeSchemaType, normalizeValue, normalizeWhereForSparql, parseCallMessage, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, requireSingleParent, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString, valueToLiteralIri };