@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.cjs CHANGED
@@ -141,7 +141,12 @@ function nextId() {
141
141
  * for the next socket is safe for writes too. This covers an executor that
142
142
  * is still binding its port (about 1.5 s with the reconnect backoff). */
143
143
  const MAX_CONNECT_ATTEMPTS = 3;
144
- const closedError = () => new RpcError(503, 'WebSocket connection closed');
144
+ const closedError = (reason) => new RpcError(503, reason || 'WebSocket connection closed');
145
+ /** Close code for "try again later": the executor's wallet is locked, so it cannot check the
146
+ * token yet. The token may be good: reconnect as for any close, and pass the reason on. */
147
+ const CLOSE_TRY_AGAIN_LATER = 1013;
148
+ /** Close code the executor uses when the socket's token opens no session, expired or was revoked. */
149
+ const CLOSE_AUTH_FAILED = 1008;
145
150
  class ApiClient {
146
151
  constructor(baseUrl, token, webSocketImpl, fetchImpl) {
147
152
  // ── WebSocket ───────────────────────────────────────────────────────────
@@ -152,6 +157,10 @@ class ApiClient {
152
157
  /** `on()` handlers by event type; a type with none has no entry. */
153
158
  this._handlers = new Map();
154
159
  this._reconnectCallbacks = new Set();
160
+ this._authFailedCallbacks = new Set();
161
+ /** Set once the executor refused the token: the reason. The client then
162
+ * never connects again; a new token needs a new client. */
163
+ this._authFailed = null;
155
164
  this._hasConnectedOnce = false;
156
165
  this._pendingCalls = new Map();
157
166
  this._wsReconnectTimer = null;
@@ -187,6 +196,8 @@ class ApiClient {
187
196
  _ensureWs() {
188
197
  if (this._ws)
189
198
  return;
199
+ if (this._authFailed !== null)
200
+ throw new RpcError(401, this._authFailed);
190
201
  const WsImpl = this._webSocketImpl ?? globalThis.WebSocket;
191
202
  const ws = new WsImpl(this._getWsUrl());
192
203
  this._ws = ws;
@@ -195,9 +206,17 @@ class ApiClient {
195
206
  resolve();
196
207
  this._onOpen(ws);
197
208
  };
198
- ws.onclose = () => {
199
- reject(closedError());
200
- this._onClose(ws);
209
+ ws.onclose = (event) => {
210
+ // Classify the close for watchApplied() as for every other waiting call.
211
+ reject(event?.code === CLOSE_AUTH_FAILED
212
+ ? new RpcError(401, event.reason || 'token expired or revoked')
213
+ : closedError(event?.code === CLOSE_TRY_AGAIN_LATER ? event.reason : undefined));
214
+ if (event?.code === CLOSE_AUTH_FAILED && this._ws === ws) {
215
+ this._failAuth(event.reason || 'Unauthorized access: the token expired or was revoked');
216
+ }
217
+ else {
218
+ this._onClose(ws, event?.code === CLOSE_TRY_AGAIN_LATER ? event.reason : undefined);
219
+ }
201
220
  };
202
221
  });
203
222
  // Only watchApplied() awaits this; a close before open is not an error otherwise.
@@ -217,10 +236,15 @@ class ApiClient {
217
236
  if (!pending)
218
237
  return; // late reply to a timed-out or aborted call, or a cancel ack
219
238
  const error = parsed.error;
220
- if (error)
221
- pending.reject(new RpcError(error.code ?? 500, error.message ?? 'Unknown error'));
222
- else
239
+ if (!error) {
223
240
  pending.resolve(parsed.result);
241
+ return;
242
+ }
243
+ const rpcError = new RpcError(error.code ?? 500, error.message ?? 'Unknown error');
244
+ pending.reject(rpcError);
245
+ // The executor answers 401 only when the token stopped working, then closes the socket.
246
+ if (rpcError.status === 401)
247
+ this._failAuth(rpcError.body);
224
248
  return;
225
249
  }
226
250
  if (parsed.type === 'pong')
@@ -269,7 +293,8 @@ class ApiClient {
269
293
  }
270
294
  this._hasConnectedOnce = true;
271
295
  }
272
- _onClose(ws) {
296
+ /** `reason` is set when the executor asked to try again later; calls that fail carry it. */
297
+ _onClose(ws, reason) {
273
298
  // A socket closed by _closeWs() can report after a new one exists.
274
299
  if (this._ws !== ws)
275
300
  return;
@@ -284,12 +309,25 @@ class ApiClient {
284
309
  pending.retry = false;
285
310
  }
286
311
  else {
287
- pending.reject(closedError());
312
+ pending.reject(closedError(reason));
288
313
  }
289
314
  }
290
315
  if (this._handlers.size > 0 || this._pendingCalls.size > 0)
291
316
  this._scheduleReconnect();
292
317
  }
318
+ /** The executor refused the token: fail every call with 401, stop
319
+ * reconnecting and tell the `onAuthFailed` callbacks, once. */
320
+ _failAuth(reason) {
321
+ if (this._authFailed !== null)
322
+ return;
323
+ this._authFailed = reason;
324
+ const error = new RpcError(401, reason);
325
+ for (const pending of this._pendingCalls.values())
326
+ pending.reject(error);
327
+ this._closeWs();
328
+ for (const cb of [...this._authFailedCallbacks])
329
+ callSafely(cb, 'Error in auth-failed callback:', reason);
330
+ }
293
331
  _startPing() {
294
332
  this._stopPing();
295
333
  this._wsPingTimer = setInterval(() => {
@@ -305,7 +343,7 @@ class ApiClient {
305
343
  }
306
344
  }
307
345
  _scheduleReconnect() {
308
- if (this._wsReconnectTimer)
346
+ if (this._wsReconnectTimer || this._authFailed !== null)
309
347
  return;
310
348
  const delay = this._wsReconnectDelay;
311
349
  this._wsReconnectDelay = Math.min(this._wsReconnectDelay * 2, MAX_RECONNECT_DELAY_MS);
@@ -405,7 +443,9 @@ class ApiClient {
405
443
  regs.add(reg);
406
444
  this._scheduleWatch();
407
445
  }
408
- this._ensureWs();
446
+ // A client whose token was refused keeps the handler but opens no socket.
447
+ if (this._authFailed === null)
448
+ this._ensureWs();
409
449
  return () => {
410
450
  const regs = this._handlers.get(type);
411
451
  if (!regs?.delete(reg))
@@ -472,10 +512,13 @@ class ApiClient {
472
512
  if (key === this._watching)
473
513
  return;
474
514
  this._watching = key;
475
- this._watchSent = this._request('events.watch', events).then(() => { this._watchRetries = 0; }, (e) => {
515
+ const sent = this._request('events.watch', events).then(() => { this._watchRetries = 0; }, (e) => {
476
516
  if (this._watching !== key)
477
517
  return;
478
518
  this._watching = null;
519
+ // A refused token (401) gets no next socket: watchApplied() must not resolve.
520
+ if (e instanceof RpcError && e.status === 401)
521
+ throw e;
479
522
  // A closed socket (503) gets the watch again when the next one opens.
480
523
  if (e instanceof RpcError && e.status === 503)
481
524
  return;
@@ -487,6 +530,9 @@ class ApiClient {
487
530
  }, WATCH_RETRY_DELAY_MS);
488
531
  }
489
532
  });
533
+ // Only watchApplied() awaits this; a refused watch is not an unhandled rejection otherwise.
534
+ sent.catch(() => { });
535
+ this._watchSent = sent;
490
536
  }
491
537
  _closeWs() {
492
538
  this._stopPing();
@@ -510,6 +556,14 @@ class ApiClient {
510
556
  this._reconnectCallbacks.add(callback);
511
557
  return () => { this._reconnectCallbacks.delete(callback); };
512
558
  }
559
+ /** Register a callback that fires once when the executor refuses this
560
+ * client's token: a 401 reply, or a socket closed with code 1008. Every
561
+ * call then fails with a 401 `RpcError` and the client does not reconnect;
562
+ * build a new client to use another token. Returns an unsubscribe function. */
563
+ onAuthFailed(callback) {
564
+ this._authFailedCallbacks.add(callback);
565
+ return () => { this._authFailedCallbacks.delete(callback); };
566
+ }
513
567
  /** Close the WebSocket and reject pending calls. */
514
568
  closeAll() {
515
569
  for (const pending of this._pendingCalls.values()) {
@@ -518,6 +572,7 @@ class ApiClient {
518
572
  this._closeWs();
519
573
  this._handlers.clear();
520
574
  this._reconnectCallbacks.clear();
575
+ this._authFailedCallbacks.clear();
521
576
  // A reused client must not fire onReconnect on its next first open.
522
577
  this._hasConnectedOnce = false;
523
578
  }
@@ -1241,8 +1296,15 @@ class AgentClient {
1241
1296
  async entanglementProofPreFlight(deviceKey, deviceKeyType) {
1242
1297
  return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('agent.entanglementProofPreflight', { deviceKey, deviceKeyType });
1243
1298
  }
1244
- async requestCapability(authInfo) {
1245
- return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('agent.requestCapability', { authInfo });
1299
+ /**
1300
+ * Asks the executor for a capability token. `agent` names the agent the token will act
1301
+ * as: a managed user's email or an agent's DID; absent, the executor's main agent. That
1302
+ * agent's owner approves the request (the operator for the main agent, the user for
1303
+ * theirs). Returns the request id that {@link generateJwt} redeems with the approver's
1304
+ * six-digit code.
1305
+ */
1306
+ async requestCapability(authInfo, agent) {
1307
+ return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('agent.requestCapability', agent === undefined ? { authInfo } : { authInfo, agent });
1246
1308
  }
1247
1309
  async permitCapability(auth) {
1248
1310
  return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('agent.permitCapability', { auth });
@@ -1278,6 +1340,18 @@ class AgentClient {
1278
1340
  async verifyEmailCode(email, code, verificationType) {
1279
1341
  return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('user.verifyEmail', { email, code, verificationType });
1280
1342
  }
1343
+ /** Revokes this client's user token. The executor then closes the client's sockets. */
1344
+ async logout() {
1345
+ return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('user.logout', {});
1346
+ }
1347
+ /**
1348
+ * Revokes every token of a user issued up to now, this client's own included, and closes
1349
+ * their sockets. A user leaves out `email` (or names themselves); the operator names the
1350
+ * user. Needs AGENT_UPDATE, which a login holds. Tokens from a later login work.
1351
+ */
1352
+ async revokeAllSessions(email) {
1353
+ return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('user.revokeAllSessions', email === undefined ? {} : { email });
1354
+ }
1281
1355
  // Hosting methods
1282
1356
  async hostingUserInfo() {
1283
1357
  const info = (await __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('hosting.info', {})).userInfo ?? {
@@ -7491,7 +7565,7 @@ function extractNamespaceFromUri(uri) {
7491
7565
  return uri.substring(0, colonIdx + 1);
7492
7566
  return uri;
7493
7567
  }
7494
- /** A live SPARQL query with its latest result.
7568
+ /** A live SPARQL or model query with its latest result.
7495
7569
  *
7496
7570
  * `subscribe()` opens the query and resolves once the first result is in;
7497
7571
  * `onResult()` callbacks then get every later result. The executor sends
@@ -7505,14 +7579,20 @@ function extractNamespaceFromUri(uri) {
7505
7579
  * ```
7506
7580
  */
7507
7581
  class QuerySubscriptionProxy {
7508
- constructor(uuid, query, client) {
7582
+ /** With `className`, `query` is a model query (JSON) over that class or
7583
+ * union of classes, opened with `modelSubscribe`; results are
7584
+ * `{ instances, totalCount }`. Without it, `query` is SPARQL. */
7585
+ constructor(uuid, query, client, className) {
7509
7586
  _QuerySubscriptionProxy_instances.add(this);
7510
7587
  _QuerySubscriptionProxy_live.set(this, void 0);
7511
7588
  _QuerySubscriptionProxy_callbacks.set(this, new Set());
7512
7589
  _QuerySubscriptionProxy_initialized.set(this, void 0);
7513
7590
  _QuerySubscriptionProxy_initResolve.set(this, void 0);
7514
7591
  _QuerySubscriptionProxy_initReject.set(this, void 0);
7515
- __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");
7592
+ const open = className === undefined
7593
+ ? () => client.subscribeQuery(uuid, query)
7594
+ : () => client.modelSubscribe(uuid, className, query);
7595
+ __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_live, new LiveQuery(client, uuid, open, result => __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliver).call(this, result)), "f");
7516
7596
  __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_initialized, new Promise((resolve, reject) => {
7517
7597
  __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_initResolve, resolve, "f");
7518
7598
  __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_initReject, reject, "f");
@@ -7934,7 +8014,7 @@ class PerspectiveProxy {
7934
8014
  *
7935
8015
  * The state is not stored on the graph: the engine derives it from the
7936
8016
  * signed proposals and keeps what it derived per agent, outside the
7937
- * perspective. So no other agent — a co-owner on the same node included —
8017
+ * perspective. So no other agent — a co-owner on the same executor included —
7938
8018
  * can read or write your entries, and a link query never sees them.
7939
8019
  * `FlowInstance.findAll` / `start` call this for you.
7940
8020
  */
@@ -9911,6 +9991,8 @@ class RuntimeClient {
9911
9991
  async removeKnownLinkLanguageTemplates(addresses) {
9912
9992
  return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, "f").call('runtime.removeLinkLanguageTemplates', { addresses });
9913
9993
  }
9994
+ /** Every link-language template the executor knows, with its meta (name, description,
9995
+ * `possibleTemplateParams`). A template whose meta cannot be read is left out. */
9914
9996
  async knownLinkLanguageTemplates() {
9915
9997
  return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, "f").call('runtime.linkLanguageTemplates', {});
9916
9998
  }
@@ -17454,6 +17536,14 @@ _AIClient_apiClient = new WeakMap(), _AIClient_transcriptionUnsubscribers = new
17454
17536
  * (`query-utils.ts`, `decorators.ts`, etc.) can import types without
17455
17537
  * creating circular runtime dependencies on `Ad4mModel.ts`.
17456
17538
  */
17539
+ /** Whether this traversal follows containment rather than a named predicate. */
17540
+ function isContainmentTraversal(scope) {
17541
+ return isTraverseScope(scope) && !('predicate' in scope && scope.predicate) && !('model' in scope && scope.model);
17542
+ }
17543
+ /** Whether this scope is the containment form, `{ id }` alone. */
17544
+ function isContainedScope(scope) {
17545
+ return !isTraverseScope(scope) && !('predicate' in scope) && !('model' in scope);
17546
+ }
17457
17547
  /**
17458
17548
  * Whether this scope is a traversal rather than a single named parent.
17459
17549
  *
@@ -17499,6 +17589,12 @@ function resolveParentPredicate(parent, childCtor) {
17499
17589
  // Raw form — explicit predicate
17500
17590
  if ('predicate' in parent)
17501
17591
  return parent.predicate;
17592
+ // Containment form — one predicate per containment edge, resolved by the
17593
+ // executor from the installed classes. There is no single one to return.
17594
+ if (isContainedScope(parent) || isContainmentTraversal(parent)) {
17595
+ throw new Error('parent(): a containment scope { id } names no single predicate; the executor resolves ' +
17596
+ 'it. Use the model query path (findAll / query / subscribe) to read it.');
17597
+ }
17502
17598
  // Model form — resolve from relation metadata
17503
17599
  const { model } = parent;
17504
17600
  const relMeta = getRelationsMetadata(model);
@@ -18624,9 +18720,10 @@ class ModelQueryBuilder {
18624
18720
  * 3. **String id + model class** — same metadata scan (or field lookup if
18625
18721
  * options include `field`).
18626
18722
  * 4. **String id + string predicate** — raw escape hatch, no metadata lookup.
18627
- *
18628
- * Passing a plain string id with no second argument throws because the
18629
- * predicate cannot be resolved without a model class.
18723
+ * 5. **String id alone** — containment through the built-in `Container`:
18724
+ * the id's `ad4m://has_child` targets, and the targets of the `children`
18725
+ * relation of every class the id is an instance of. The executor
18726
+ * resolves the predicates; nothing is looked up here.
18630
18727
  *
18631
18728
  * @param idOrInstance - The parent's expression URI **or** an Ad4mModel instance
18632
18729
  * @param modelOrPredicate - A model class (predicate auto-resolved) **or** a raw predicate string
@@ -18649,6 +18746,9 @@ class ModelQueryBuilder {
18649
18746
  *
18650
18747
  * // String id + raw predicate (escape hatch)
18651
18748
  * Recipe.query(perspective).parent(cookbookId, "cookbook://recipe").get();
18749
+ *
18750
+ * // String id alone: whatever cookbookId contains
18751
+ * Recipe.query(perspective).parent(cookbookId).get();
18652
18752
  * ```
18653
18753
  */
18654
18754
  parent(idOrInstance, modelOrPredicate, options) {
@@ -18676,7 +18776,8 @@ class ModelQueryBuilder {
18676
18776
  this.queryParams.parent = { id, model: idOrInstance.constructor, ...(field && { field }) };
18677
18777
  }
18678
18778
  else {
18679
- throw new Error('parent() called with a string id requires a second argument: either a model class or a predicate string');
18779
+ // String id alone → containment form of Scope
18780
+ this.queryParams.parent = { id };
18680
18781
  }
18681
18782
  return this;
18682
18783
  }
@@ -19475,6 +19576,24 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
19475
19576
  }
19476
19577
  return instance;
19477
19578
  }
19579
+ /**
19580
+ * Put `childId` under `parent`. A containment scope `{ id }` writes through the
19581
+ * built-in `Container` (#1446): the executor runs the adder of the parent's own
19582
+ * `children` relation when its class has one (a block's `we://child`), else
19583
+ * writes `ad4m://has_child`. The other forms write their one predicate.
19584
+ */
19585
+ async function linkToParent(perspective, parent, childCtor, childId, batchId) {
19586
+ if (isContainedScope(parent)) {
19587
+ await perspective.updateSubject("ad4m://Container", parent.id, { children: { action: "adder", value: [childId] } }, batchId);
19588
+ return;
19589
+ }
19590
+ const link = new Link({
19591
+ source: parent.id,
19592
+ predicate: resolveParentPredicate(parent, childCtor),
19593
+ target: childId,
19594
+ });
19595
+ await perspective.add(link, 'shared', batchId);
19596
+ }
19478
19597
  /**
19479
19598
  * Base class for defining data models in AD4M.
19480
19599
  *
@@ -20132,7 +20251,28 @@ class Ad4mModel {
20132
20251
  query = { ...query, include: { ...expanded, ...query.include } };
20133
20252
  }
20134
20253
  const queryInput = {};
20135
- if (query.parent) {
20254
+ if (query.parent && isContainedScope(query.parent)) {
20255
+ // Containment: the executor resolves the predicates from the installed
20256
+ // classes, so only the id travels.
20257
+ queryInput.parent = { id: query.parent.id };
20258
+ }
20259
+ else if (query.parent && isContainmentTraversal(query.parent)) {
20260
+ // A traversal over containment: no predicate travels either.
20261
+ const t = query.parent;
20262
+ const traverse = { ids: t.ids };
20263
+ if (t.transitive !== undefined)
20264
+ traverse.transitive = t.transitive;
20265
+ if (t.direction !== undefined)
20266
+ traverse.direction = t.direction;
20267
+ if (t.limitPerAnchor !== undefined)
20268
+ traverse.limitPerAnchor = t.limitPerAnchor;
20269
+ if (t.levels !== undefined)
20270
+ traverse.levels = t.levels;
20271
+ if (t.maxDepth !== undefined)
20272
+ traverse.maxDepth = t.maxDepth;
20273
+ queryInput.parent = traverse;
20274
+ }
20275
+ else if (query.parent) {
20136
20276
  const parentPredicate = resolveParentPredicate(query.parent, this);
20137
20277
  // A traversal keeps its own shape on the wire: the executor reads `ids`,
20138
20278
  // and flattening it to one `id` here is how a request for a whole level
@@ -20156,6 +20296,8 @@ class Ad4mModel {
20156
20296
  traverse.limitPerAnchor = t.limitPerAnchor;
20157
20297
  if (t.levels !== undefined)
20158
20298
  traverse.levels = t.levels;
20299
+ if (t.maxDepth !== undefined)
20300
+ traverse.maxDepth = t.maxDepth;
20159
20301
  queryInput.parent = traverse;
20160
20302
  }
20161
20303
  else {
@@ -21120,14 +21262,7 @@ class Ad4mModel {
21120
21262
  if (options?.parent && !options?.batchId) {
21121
21263
  const batchId = await perspective.createBatch();
21122
21264
  await instance.save(batchId);
21123
- const parent = requireSingleParent(options.parent);
21124
- const predicate = resolveParentPredicate(parent, this);
21125
- const link = new Link({
21126
- source: parent.id,
21127
- predicate,
21128
- target: instance.id,
21129
- });
21130
- await perspective.add(link, 'shared', batchId);
21265
+ await linkToParent(perspective, requireSingleParent(options.parent), this, instance.id, batchId);
21131
21266
  await perspective.commitBatch(batchId);
21132
21267
  // Hydrate the instance now that the batch has been committed (mirrors the
21133
21268
  // behaviour of save() when it manages its own batch).
@@ -21137,14 +21272,7 @@ class Ad4mModel {
21137
21272
  await instance.save(options?.batchId);
21138
21273
  // Create parent → child link if a parent scope was provided
21139
21274
  if (options?.parent) {
21140
- const parent = requireSingleParent(options.parent);
21141
- const predicate = resolveParentPredicate(parent, this);
21142
- const link = new Link({
21143
- source: parent.id,
21144
- predicate,
21145
- target: instance.id,
21146
- });
21147
- await perspective.add(link, 'shared', options?.batchId);
21275
+ await linkToParent(perspective, requireSingleParent(options.parent), this, instance.id, options?.batchId);
21148
21276
  }
21149
21277
  return instance;
21150
21278
  }
@@ -21551,6 +21679,15 @@ class Ad4mClient {
21551
21679
  on(type, handler, filter) {
21552
21680
  return __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f").on(type, handler, filter);
21553
21681
  }
21682
+ /**
21683
+ * Call `callback` once when the executor refuses this client's token
21684
+ * (expired, revoked, or no session). Every call then fails with a 401
21685
+ * `RpcError` and the client stops reconnecting: log in again and build a
21686
+ * new client. Returns a function that removes the callback.
21687
+ */
21688
+ onAuthFailed(callback) {
21689
+ return __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f").onAuthFailed(callback);
21690
+ }
21554
21691
  /** Close all event connections and clear in-memory caches */
21555
21692
  close() {
21556
21693
  __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f").clearByDidCache();
@@ -21702,13 +21839,13 @@ class LanguageLanguageInput {
21702
21839
  * const runs = await InterpretationRun.findAll(perspective);
21703
21840
  * const configs = await AutoProcessorConfig.findAll(perspective);
21704
21841
  */
21705
- var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
21842
+ var __decorate$3 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
21706
21843
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
21707
21844
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21708
21845
  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;
21709
21846
  return c > 3 && r && Object.defineProperty(target, key, r), r;
21710
21847
  };
21711
- var __metadata$2 = (undefined && undefined.__metadata) || function (k, v) {
21848
+ var __metadata$3 = (undefined && undefined.__metadata) || function (k, v) {
21712
21849
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
21713
21850
  };
21714
21851
  // ── AutoProcessorConfig ─────────────────────────────────────────────────────
@@ -21749,71 +21886,71 @@ exports.AutoProcessorConfig = class AutoProcessorConfig extends Ad4mModel {
21749
21886
  // `batchMax` + `claimTtlMs` — the Rust SDNA takes the same shape.
21750
21887
  }
21751
21888
  };
21752
- __decorate$2([
21889
+ __decorate$3([
21753
21890
  Property({ through: "ad4m://processor_id", required: true, identity: true }),
21754
- __metadata$2("design:type", String)
21891
+ __metadata$3("design:type", String)
21755
21892
  ], exports.AutoProcessorConfig.prototype, "processorId", void 0);
21756
- __decorate$2([
21893
+ __decorate$3([
21757
21894
  Property({ through: "ad4m://source_scope_query", required: true }),
21758
- __metadata$2("design:type", String)
21895
+ __metadata$3("design:type", String)
21759
21896
  ], exports.AutoProcessorConfig.prototype, "sourceScopeQuery", void 0);
21760
- __decorate$2([
21897
+ __decorate$3([
21761
21898
  Optional({ through: "ad4m://base_prefix" }),
21762
- __metadata$2("design:type", String)
21899
+ __metadata$3("design:type", String)
21763
21900
  ], exports.AutoProcessorConfig.prototype, "basePrefix", void 0);
21764
- __decorate$2([
21901
+ __decorate$3([
21765
21902
  HasMany({ through: "ad4m://interpretation_class", datatype: "xsd:string" }),
21766
- __metadata$2("design:type", Array)
21903
+ __metadata$3("design:type", Array)
21767
21904
  ], exports.AutoProcessorConfig.prototype, "interpretationClasses", void 0);
21768
- __decorate$2([
21905
+ __decorate$3([
21769
21906
  HasMany({ through: "ad4m://flow", datatype: "xsd:string" }),
21770
- __metadata$2("design:type", Array)
21907
+ __metadata$3("design:type", Array)
21771
21908
  ], exports.AutoProcessorConfig.prototype, "flows", void 0);
21772
- __decorate$2([
21909
+ __decorate$3([
21773
21910
  Property({ through: "ad4m://debounce_ms", required: true }),
21774
- __metadata$2("design:type", String)
21911
+ __metadata$3("design:type", String)
21775
21912
  ], exports.AutoProcessorConfig.prototype, "debounceMs", void 0);
21776
- __decorate$2([
21913
+ __decorate$3([
21777
21914
  Optional({ through: "ad4m://batch_min" }),
21778
- __metadata$2("design:type", String)
21915
+ __metadata$3("design:type", String)
21779
21916
  ], exports.AutoProcessorConfig.prototype, "batchMin", void 0);
21780
- __decorate$2([
21917
+ __decorate$3([
21781
21918
  Property({ through: "ad4m://batch_max", required: true }),
21782
- __metadata$2("design:type", String)
21919
+ __metadata$3("design:type", String)
21783
21920
  ], exports.AutoProcessorConfig.prototype, "batchMax", void 0);
21784
- __decorate$2([
21921
+ __decorate$3([
21785
21922
  Optional({ through: "ad4m://max_wait_ms" }),
21786
- __metadata$2("design:type", String)
21923
+ __metadata$3("design:type", String)
21787
21924
  ], exports.AutoProcessorConfig.prototype, "maxWaitMs", void 0);
21788
- __decorate$2([
21925
+ __decorate$3([
21789
21926
  Property({ through: "ad4m://claim_ttl_ms", required: true }),
21790
- __metadata$2("design:type", String)
21927
+ __metadata$3("design:type", String)
21791
21928
  ], exports.AutoProcessorConfig.prototype, "claimTtlMs", void 0);
21792
- __decorate$2([
21929
+ __decorate$3([
21793
21930
  Optional({ through: "ad4m://source_window_ms" }),
21794
- __metadata$2("design:type", String)
21931
+ __metadata$3("design:type", String)
21795
21932
  ], exports.AutoProcessorConfig.prototype, "sourceWindowMs", void 0);
21796
- __decorate$2([
21933
+ __decorate$3([
21797
21934
  Optional({ through: "ad4m://dedup_strategy" }),
21798
- __metadata$2("design:type", String)
21935
+ __metadata$3("design:type", String)
21799
21936
  ], exports.AutoProcessorConfig.prototype, "dedupStrategy", void 0);
21800
- __decorate$2([
21937
+ __decorate$3([
21801
21938
  Optional({ through: "ad4m://existing_scope" }),
21802
- __metadata$2("design:type", String)
21939
+ __metadata$3("design:type", String)
21803
21940
  ], exports.AutoProcessorConfig.prototype, "existingScope", void 0);
21804
- __decorate$2([
21941
+ __decorate$3([
21805
21942
  Optional({ through: "ad4m://mint_scope" }),
21806
- __metadata$2("design:type", String)
21943
+ __metadata$3("design:type", String)
21807
21944
  ], exports.AutoProcessorConfig.prototype, "mintScope", void 0);
21808
- __decorate$2([
21945
+ __decorate$3([
21809
21946
  Optional({ through: "ad4m://max_tool_calls" }),
21810
- __metadata$2("design:type", String)
21947
+ __metadata$3("design:type", String)
21811
21948
  ], exports.AutoProcessorConfig.prototype, "maxToolCalls", void 0);
21812
- __decorate$2([
21949
+ __decorate$3([
21813
21950
  Optional({ through: "ad4m://emit_debug_events", resolveLanguage: "literal" }),
21814
- __metadata$2("design:type", String)
21951
+ __metadata$3("design:type", String)
21815
21952
  ], exports.AutoProcessorConfig.prototype, "emitDebugEvents", void 0);
21816
- exports.AutoProcessorConfig = __decorate$2([
21953
+ exports.AutoProcessorConfig = __decorate$3([
21817
21954
  Model$1({ name: "AutoProcessor" })
21818
21955
  ], exports.AutoProcessorConfig);
21819
21956
  // ── InterpretationRun ───────────────────────────────────────────────────────
@@ -21837,39 +21974,39 @@ exports.InterpretationRun = class InterpretationRun extends Ad4mModel {
21837
21974
  this.sources = [];
21838
21975
  }
21839
21976
  };
21840
- __decorate$2([
21977
+ __decorate$3([
21841
21978
  Property({ through: "ad4m://interp/run_id", required: true, identity: true }),
21842
- __metadata$2("design:type", String)
21979
+ __metadata$3("design:type", String)
21843
21980
  ], exports.InterpretationRun.prototype, "runId", void 0);
21844
- __decorate$2([
21981
+ __decorate$3([
21845
21982
  Optional({ through: "ad4m://interp/model" }),
21846
- __metadata$2("design:type", String)
21983
+ __metadata$3("design:type", String)
21847
21984
  ], exports.InterpretationRun.prototype, "model", void 0);
21848
- __decorate$2([
21985
+ __decorate$3([
21849
21986
  Optional({ through: "ad4m://interp/prompt_version" }),
21850
- __metadata$2("design:type", String)
21987
+ __metadata$3("design:type", String)
21851
21988
  ], exports.InterpretationRun.prototype, "promptVersion", void 0);
21852
- __decorate$2([
21989
+ __decorate$3([
21853
21990
  Optional({ through: "ad4m://interp/ran_at" }),
21854
- __metadata$2("design:type", String)
21991
+ __metadata$3("design:type", String)
21855
21992
  ], exports.InterpretationRun.prototype, "ranAt", void 0);
21856
- __decorate$2([
21993
+ __decorate$3([
21857
21994
  Optional({ through: "ad4m://interp/processor" }),
21858
- __metadata$2("design:type", String)
21995
+ __metadata$3("design:type", String)
21859
21996
  ], exports.InterpretationRun.prototype, "processor", void 0);
21860
- __decorate$2([
21997
+ __decorate$3([
21861
21998
  HasMany({ through: "ad4m://interp/sources", datatype: "xsd:string" }),
21862
- __metadata$2("design:type", Array)
21999
+ __metadata$3("design:type", Array)
21863
22000
  ], exports.InterpretationRun.prototype, "sources", void 0);
21864
- __decorate$2([
22001
+ __decorate$3([
21865
22002
  Optional({ through: "ad4m://interp/debug_prompt", resolveLanguage: "literal" }),
21866
- __metadata$2("design:type", String)
22003
+ __metadata$3("design:type", String)
21867
22004
  ], exports.InterpretationRun.prototype, "debugPrompt", void 0);
21868
- __decorate$2([
22005
+ __decorate$3([
21869
22006
  Optional({ through: "ad4m://interp/debug_response", resolveLanguage: "literal" }),
21870
- __metadata$2("design:type", String)
22007
+ __metadata$3("design:type", String)
21871
22008
  ], exports.InterpretationRun.prototype, "debugResponse", void 0);
21872
- exports.InterpretationRun = __decorate$2([
22009
+ exports.InterpretationRun = __decorate$3([
21873
22010
  Model$1({ name: "InterpretationRun" })
21874
22011
  ], exports.InterpretationRun);
21875
22012
  // ── InterpretationOverlay ───────────────────────────────────────────────────
@@ -21899,15 +22036,15 @@ exports.InterpretationOverlay = class InterpretationOverlay extends Ad4mModel {
21899
22036
  this.kind = "";
21900
22037
  }
21901
22038
  };
21902
- __decorate$2([
22039
+ __decorate$3([
21903
22040
  Property({ through: "ad4m://interp/kind", required: true }),
21904
- __metadata$2("design:type", String)
22041
+ __metadata$3("design:type", String)
21905
22042
  ], exports.InterpretationOverlay.prototype, "kind", void 0);
21906
- __decorate$2([
22043
+ __decorate$3([
21907
22044
  Optional({ through: "ad4m://interp/run" }),
21908
- __metadata$2("design:type", String)
22045
+ __metadata$3("design:type", String)
21909
22046
  ], exports.InterpretationOverlay.prototype, "run", void 0);
21910
- exports.InterpretationOverlay = __decorate$2([
22047
+ exports.InterpretationOverlay = __decorate$3([
21911
22048
  Model$1({ name: "InterpretationOverlay" })
21912
22049
  ], exports.InterpretationOverlay);
21913
22050
 
@@ -21931,13 +22068,13 @@ exports.InterpretationOverlay = __decorate$2([
21931
22068
  * - the SDNA-parity test locks TS/Rust drift against
21932
22069
  * `rust-executor/src/perspectives/hardwired_sdna/flow_transition_proposal.json`.
21933
22070
  */
21934
- var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22071
+ var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
21935
22072
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
21936
22073
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21937
22074
  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;
21938
22075
  return c > 3 && r && Object.defineProperty(target, key, r), r;
21939
22076
  };
21940
- var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22077
+ var __metadata$2 = (undefined && undefined.__metadata) || function (k, v) {
21941
22078
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
21942
22079
  };
21943
22080
  /**
@@ -22044,55 +22181,55 @@ exports.FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel
22044
22181
  // of the proposal's own links (all written together during create_subject).
22045
22182
  }
22046
22183
  };
22047
- __decorate$1([
22184
+ __decorate$2([
22048
22185
  Property({ through: "ad4m://flow/instance", required: true, identity: true }),
22049
- __metadata$1("design:type", String)
22186
+ __metadata$2("design:type", String)
22050
22187
  ], exports.FlowTransitionProposal.prototype, "flowInstance", void 0);
22051
- __decorate$1([
22188
+ __decorate$2([
22052
22189
  Property({ through: "ad4m://flow/from_state", required: true }),
22053
- __metadata$1("design:type", String)
22190
+ __metadata$2("design:type", String)
22054
22191
  ], exports.FlowTransitionProposal.prototype, "fromState", void 0);
22055
- __decorate$1([
22192
+ __decorate$2([
22056
22193
  Property({ through: "ad4m://flow/to_state", required: true }),
22057
- __metadata$1("design:type", String)
22194
+ __metadata$2("design:type", String)
22058
22195
  ], exports.FlowTransitionProposal.prototype, "toState", void 0);
22059
- __decorate$1([
22196
+ __decorate$2([
22060
22197
  Property({ through: "ad4m://flow/proposer", required: true, getter: PROPOSER_GETTER, datatype: "xsd:string" }),
22061
- __metadata$1("design:type", String)
22198
+ __metadata$2("design:type", String)
22062
22199
  ], exports.FlowTransitionProposal.prototype, "proposer", void 0);
22063
- __decorate$1([
22200
+ __decorate$2([
22064
22201
  HasMany({ through: "ad4m://flow/evidence", datatype: "xsd:string" }),
22065
- __metadata$1("design:type", Array)
22202
+ __metadata$2("design:type", Array)
22066
22203
  ], exports.FlowTransitionProposal.prototype, "evidence", void 0);
22067
- __decorate$1([
22204
+ __decorate$2([
22068
22205
  Property({ through: "ad4m://flow/evidence_hashes", required: true }),
22069
- __metadata$1("design:type", String)
22206
+ __metadata$2("design:type", String)
22070
22207
  ], exports.FlowTransitionProposal.prototype, "evidenceHashes", void 0);
22071
- __decorate$1([
22208
+ __decorate$2([
22072
22209
  HasMany({ through: "ad4m://flow/output", datatype: "xsd:string" }),
22073
- __metadata$1("design:type", Array)
22210
+ __metadata$2("design:type", Array)
22074
22211
  ], exports.FlowTransitionProposal.prototype, "outputs", void 0);
22075
- __decorate$1([
22212
+ __decorate$2([
22076
22213
  Property({ through: "ad4m://flow/outputs_hash" }),
22077
- __metadata$1("design:type", String)
22214
+ __metadata$2("design:type", String)
22078
22215
  ], exports.FlowTransitionProposal.prototype, "outputsHash", void 0);
22079
- __decorate$1([
22216
+ __decorate$2([
22080
22217
  Property({ through: "ad4m://flow/nonce" }),
22081
- __metadata$1("design:type", String)
22218
+ __metadata$2("design:type", String)
22082
22219
  ], exports.FlowTransitionProposal.prototype, "nonce", void 0);
22083
- __decorate$1([
22220
+ __decorate$2([
22084
22221
  Optional({ through: "ad4m://flow/run_uri" }),
22085
- __metadata$1("design:type", String)
22222
+ __metadata$2("design:type", String)
22086
22223
  ], exports.FlowTransitionProposal.prototype, "runUri", void 0);
22087
- __decorate$1([
22224
+ __decorate$2([
22088
22225
  Optional({ through: "ad4m://flow/rationale" }),
22089
- __metadata$1("design:type", String)
22226
+ __metadata$2("design:type", String)
22090
22227
  ], exports.FlowTransitionProposal.prototype, "rationale", void 0);
22091
- __decorate$1([
22228
+ __decorate$2([
22092
22229
  HasMany({ through: "ad4m://acceptedBy", getter: ACCEPTED_BY_GETTER, readOnly: true }),
22093
- __metadata$1("design:type", Array)
22230
+ __metadata$2("design:type", Array)
22094
22231
  ], exports.FlowTransitionProposal.prototype, "acceptedBy", void 0);
22095
- exports.FlowTransitionProposal = __decorate$1([
22232
+ exports.FlowTransitionProposal = __decorate$2([
22096
22233
  Model$1({ name: "FlowTransitionProposal" })
22097
22234
  ], exports.FlowTransitionProposal);
22098
22235
  // ── FlowInstanceRecord ──────────────────────────────────────────────────────
@@ -22152,25 +22289,25 @@ exports.FlowInstanceRecord = class FlowInstanceRecord extends Ad4mModel {
22152
22289
  // of the instance's own links (all written together during `mint_flow_instance`).
22153
22290
  }
22154
22291
  };
22155
- __decorate$1([
22292
+ __decorate$2([
22156
22293
  Property({ through: "ad4m://flow/flow_uri", required: true, identity: true }),
22157
- __metadata$1("design:type", String)
22294
+ __metadata$2("design:type", String)
22158
22295
  ], exports.FlowInstanceRecord.prototype, "flowUri", void 0);
22159
- __decorate$1([
22296
+ __decorate$2([
22160
22297
  Property({ through: "ad4m://flow/base", required: true }),
22161
- __metadata$1("design:type", String)
22298
+ __metadata$2("design:type", String)
22162
22299
  ], exports.FlowInstanceRecord.prototype, "subject", void 0);
22163
- exports.FlowInstanceRecord = __decorate$1([
22300
+ exports.FlowInstanceRecord = __decorate$2([
22164
22301
  Model$1({ name: "FlowInstance" })
22165
22302
  ], exports.FlowInstanceRecord);
22166
22303
 
22167
- var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22304
+ var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22168
22305
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22169
22306
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22170
22307
  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;
22171
22308
  return c > 3 && r && Object.defineProperty(target, key, r), r;
22172
22309
  };
22173
- var __metadata = (undefined && undefined.__metadata) || function (k, v) {
22310
+ var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22174
22311
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22175
22312
  };
22176
22313
  /**
@@ -22206,14 +22343,74 @@ exports.TextContent = class TextContent extends Ad4mModel {
22206
22343
  };
22207
22344
  /** The URI the executor reads it by. */
22208
22345
  exports.TextContent.builtinUri = "ad4m://TextContent";
22209
- __decorate([
22346
+ __decorate$1([
22210
22347
  Property({ through: "ad4m://text" }),
22211
- __metadata("design:type", String)
22348
+ __metadata$1("design:type", String)
22212
22349
  ], exports.TextContent.prototype, "text", void 0);
22213
- exports.TextContent = __decorate([
22350
+ exports.TextContent = __decorate$1([
22214
22351
  Model$1({ name: "TextContent", abstract: true })
22215
22352
  ], exports.TextContent);
22216
22353
 
22354
+ var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22355
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22356
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22357
+ 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;
22358
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
22359
+ };
22360
+ var __metadata = (undefined && undefined.__metadata) || function (k, v) {
22361
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22362
+ };
22363
+ /**
22364
+ * The built-in abstract class `Container { children }` (#1446): what holds
22365
+ * other records — a channel, a thread, a post, a call, a document, a board.
22366
+ *
22367
+ * X is contained in P when `P ad4m://has_child X` exists, whatever P is (an
22368
+ * instance of any class, or a node no class describes, such as
22369
+ * `ad4m://self`), or when P is an instance of a class whose `children`
22370
+ * relation (by name, or aliased to `children`) links X:
22371
+ *
22372
+ * ```typescript
22373
+ * @Model({ name: "Block", implements: [Container] })
22374
+ * class Block extends Ad4mModel {
22375
+ * @HasMany({ through: "we://child", alias: { Container: "children" } })
22376
+ * blocks: string[] = [];
22377
+ * }
22378
+ *
22379
+ * // Messages held by P, through has_child or a Block's we://child:
22380
+ * await Message.findAll(perspective, { parent: { id: P } });
22381
+ * // Everything that holds X:
22382
+ * await Container.findAll(perspective, { parent: { ids: [X], direction: "in" } });
22383
+ * ```
22384
+ *
22385
+ * A row's `children` is everything it holds, merged across its classes. A
22386
+ * node no class describes is a row of its own when it holds something by
22387
+ * `has_child`. Always scope a `Container` query (`where: { id }`, a
22388
+ * `children` filter or `parent`): unscoped, it reads every holder in the
22389
+ * perspective.
22390
+ *
22391
+ * Built in: the executor declares it (mirrors
22392
+ * `rust-executor/src/perspectives/hardwired_sdna/container.json`) and reads
22393
+ * it by its URI, `ad4m://Container`, so a perspective never stores it and an
22394
+ * app class named `Container` does not replace it. `register()` on it writes
22395
+ * nothing.
22396
+ */
22397
+ exports.Container = class Container extends Ad4mModel {
22398
+ constructor() {
22399
+ super(...arguments);
22400
+ /** What it holds, whatever their class. */
22401
+ this.children = [];
22402
+ }
22403
+ };
22404
+ /** The URI the executor reads it by. */
22405
+ exports.Container.builtinUri = "ad4m://Container";
22406
+ __decorate([
22407
+ HasMany({ through: "ad4m://has_child" }),
22408
+ __metadata("design:type", Array)
22409
+ ], exports.Container.prototype, "children", void 0);
22410
+ exports.Container = __decorate([
22411
+ Model$1({ name: "Container", abstract: true })
22412
+ ], exports.Container);
22413
+
22217
22414
  /**
22218
22415
  * `FlowInstance` — object-oriented wrapper for a running flow.
22219
22416
  *
@@ -22802,6 +22999,107 @@ function parseLitBoolean(val) {
22802
22999
  * module (`plugins/ad4m/wakerSubscriptionManager.ts`) rather than carrying its
22803
23000
  * own copy. Any behaviour change belongs here.
22804
23001
  */
23002
+ /** A letter, combining mark, digit or underscore: what a term must not touch. */
23003
+ const WORD_CHAR = "[\\p{L}\\p{M}\\p{N}_]";
23004
+ /**
23005
+ * The elements a message's HTML is made of. A `<` before any other name is text:
23006
+ * We stores plain text, where "<hey Data> can you look" is words.
23007
+ */
23008
+ const ELEMENT = "a|abbr|b|bdi|bdo|blockquote|br|caption|center|cite|code|col|colgroup|dd|del|details|dfn|div|dl|dt|em|" +
23009
+ "figcaption|figure|font|h[1-6]|hr|i|img|ins|kbd|label|li|mark|ol|p|pre|q|s|samp|section|article|small|" +
23010
+ "span|strike|strong|sub|summary|sup|table|tbody|td|tfoot|th|thead|time|tr|u|ul|var|wbr|script|style";
23011
+ /** An attribute: a name, then optionally `=` and a quoted value (which may hold `>`) or an unquoted one. */
23012
+ const ATTRIBUTE = `\\s+[A-Za-z_:][-\\w:.]*(?:\\s*=\\s*(?:"[^"]*"|'[^']*'|[^\\s"'=<>\`]+))?`;
23013
+ /**
23014
+ * Markup: a comment, a `<script>`/`<style>` element with its contents, or a tag of
23015
+ * a known element whose rest is a valid attribute list. "a < b" and
23016
+ * "if a <b then ask Data, else c -> d" are text: the comma is no attribute.
23017
+ */
23018
+ const TAG = new RegExp(`<!--[\\s\\S]*?-->` +
23019
+ `|<(script|style)(?=[\\s/>])(?:${ATTRIBUTE})*\\s*>[\\s\\S]*?<\\/\\1\\s*>` +
23020
+ `|<(?:${ELEMENT})(?=[\\s/>])(?:${ATTRIBUTE})*\\s*\\/?>` +
23021
+ `|<\\/(?:${ELEMENT})\\s*>`, "gi");
23022
+ /** Tags that break a line: replaced by a space, so `<p>hi</p><p>Data</p>` keeps "Data" a word. */
23023
+ const BREAKING_TAG = /^<\/?(?:p|div|br|hr|li|ul|ol|h[1-6]|blockquote|pre|tr|td|th|table|section|article)\b/i;
23024
+ /**
23025
+ * The attributes a mention puts its target's DID in: Flux's `<a data-type="mention"
23026
+ * href="did:…">`, older Flux messages' `<span data-id="did:…">`, and We's editor chip
23027
+ * `<span class="we-mention" data-did="did:…">`.
23028
+ */
23029
+ const ATTRIBUTES = new RegExp(ATTRIBUTE, "g");
23030
+ const MENTION_TARGET = /^\s+(?:href|data-id|data-did)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))$/i;
23031
+ /**
23032
+ * How much of a record's text the word check reads. Dropping markup costs time
23033
+ * quadratic in a run of unclosed `<script>`, `<style>` or `<!--` openers, so a
23034
+ * very long text could hold the event loop for seconds, and a row that holds
23035
+ * no term is checked again on every result while it is in the window. A term
23036
+ * past this many characters does not wake.
23037
+ */
23038
+ const MENTION_TEXT_LIMIT = 16384;
23039
+ const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
23040
+ function decodeEntities(s) {
23041
+ return s.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi, (whole, ref) => {
23042
+ if (ref[0] !== "#")
23043
+ return ENTITIES[ref.toLowerCase()] ?? whole;
23044
+ const code = ref[1] === "x" || ref[1] === "X" ? parseInt(ref.slice(2), 16) : parseInt(ref.slice(1), 10);
23045
+ return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : whole;
23046
+ });
23047
+ }
23048
+ /**
23049
+ * What a reader sees of `text`, and the DIDs its mentions point at. `text` may be
23050
+ * HTML (TextContent allows it): tag names and attributes are markup, not words, so
23051
+ * a bot named "Data" must not wake on `data-type="mention"` in a mention of
23052
+ * someone else. Plain text passes through unchanged, apart from entities.
23053
+ */
23054
+ function readableParts(text) {
23055
+ const targets = [];
23056
+ const visible = text.replace(TAG, (tag, scriptOrStyle) => {
23057
+ if (scriptOrStyle)
23058
+ return " ";
23059
+ if (tag.startsWith("<!--"))
23060
+ return "";
23061
+ // Parse complete attributes first: a DID-shaped string inside `title`
23062
+ // is not a target attribute and must not wake an agent.
23063
+ for (const attribute of tag.matchAll(ATTRIBUTES)) {
23064
+ const target = MENTION_TARGET.exec(attribute[0]);
23065
+ if (target)
23066
+ targets.push(decodeEntities(target[1] ?? target[2] ?? target[3]));
23067
+ }
23068
+ return BREAKING_TAG.test(tag) ? " " : "";
23069
+ });
23070
+ return { visible: decodeEntities(visible), targets };
23071
+ }
23072
+ /**
23073
+ * Whether `text` holds one of `terms` as a whole word, case-insensitively:
23074
+ * "Data" is in "hi Data!", "@data" and "Data's turn", not in "metadata" or
23075
+ * "database". A term is matched literally (regex characters, quotes) and must
23076
+ * not touch a letter, mark, digit or underscore on either side, so a name
23077
+ * that starts or ends with punctuation still matches. Same rule as #1459's
23078
+ * SPARQL `(?:^|\W)term(?:\W|$)`.
23079
+ *
23080
+ * The rule runs on the visible text only: in HTML, tags and attributes are
23081
+ * dropped and entities decoded first. A mention's target attribute
23082
+ * (`href`, `data-id`, `data-did`) matches an exact, case-sensitive DID term, which
23083
+ * is how a mention by DID is found when the DID is not in the visible text.
23084
+ *
23085
+ * The mention query's `contains` matches substrings (model query has no word
23086
+ * match); this is the check that keeps "data" from waking on "metadata".
23087
+ * It reads the first {@link MENTION_TEXT_LIMIT} characters only.
23088
+ */
23089
+ function holdsAWholeWordTerm(text, terms) {
23090
+ const { visible, targets } = readableParts(text.slice(0, MENTION_TEXT_LIMIT));
23091
+ return terms.some((term) => {
23092
+ if (!term)
23093
+ return false;
23094
+ if (term.startsWith("did:") && targets.includes(term))
23095
+ return true;
23096
+ const escaped = term.replace(/[\\^$.*+?()[\]{}|\/]/g, "\\$&");
23097
+ return new RegExp(`(?<!${WORD_CHAR})${escaped}(?!${WORD_CHAR})`, "iu").test(visible);
23098
+ });
23099
+ }
23100
+ /** The built-in `Container` (`Container.builtinUri`; not imported, so the
23101
+ * plugin bundle does not pull in the model layer). */
23102
+ const CONTAINER = "ad4m://Container";
22805
23103
  /**
22806
23104
  * Add a short cause hint to known subscription failures.
22807
23105
  * The executor needs its main key to register a live query; on a restarted
@@ -22811,13 +23109,13 @@ function hintFor(msg) {
22811
23109
  // "Executor is locked" is the current executor's message; "main key not
22812
23110
  // found" is what older executors (and unrelated key lookups) say for the
22813
23111
  // same locked state. Either way the caller cannot fix it themselves: keys
22814
- // live in memory only, so every restart locks the node again and only its
23112
+ // live in memory only, so every restart locks the executor again and only its
22815
23113
  // operator can unlock it.
22816
23114
  if (/executor is locked/i.test(msg) || /main key not found/i.test(msg)) {
22817
- 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";
23115
+ 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";
22818
23116
  }
22819
23117
  if (/timed out after \d+ms/i.test(msg)) {
22820
- 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";
23118
+ 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";
22821
23119
  }
22822
23120
  return "";
22823
23121
  }
@@ -22868,6 +23166,20 @@ class WakerSubscriptionManager {
22868
23166
  /** Per-subscription set of already-processed message addresses (for mention subs)
22869
23167
  * or serialized result hash (for channel-messages subs). */
22870
23168
  this.seenMessages = new Map();
23169
+ /**
23170
+ * Per mention subscription: the addresses whose wake was delivered, or that were history when
23171
+ * the subscription opened. This, not `seenMessages`, is what gets persisted: an address joins
23172
+ * `seenMessages` as soon as it is read, while its parents are still resolving and before any
23173
+ * wake, so a restart in between must not take it as done.
23174
+ */
23175
+ this.delivered = new Map();
23176
+ /**
23177
+ * Per mention subscription: mentions read but whose wake has not been delivered yet, keyed by
23178
+ * address. They accumulate across a debounce window, so one wake names all of them.
23179
+ */
23180
+ this.undelivered = new Map();
23181
+ /** Failed wake attempts in a row per subscription, for the retry backoff. */
23182
+ this.wakeFailures = new Map();
22871
23183
  this.perspectiveClient = options.perspectiveClient;
22872
23184
  this.logger = options.logger;
22873
23185
  this.debounceMs = options.debounceMs ?? 2000;
@@ -22878,6 +23190,7 @@ class WakerSubscriptionManager {
22878
23190
  this.previousSeenMessages = options.previousSeenMessages ?? {};
22879
23191
  this.retryPendingMs = options.retryPendingMs ?? 30000;
22880
23192
  this.subscribeTimeoutMs = options.subscribeTimeoutMs ?? 15000;
23193
+ this.retryWakeMs = options.retryWakeMs ?? 5000;
22881
23194
  }
22882
23195
  /** A token identifying this attempt at subscribing `id`. */
22883
23196
  beginAttempt(id) {
@@ -22890,7 +23203,7 @@ class WakerSubscriptionManager {
22890
23203
  return token.epoch !== this.epoch || this.generations.get(id) !== token.gen;
22891
23204
  }
22892
23205
  /**
22893
- * Create a live SPARQL subscription.
23206
+ * Create a live subscription: SPARQL, or a model query when `sub.className` is set.
22894
23207
  * If a subscription with the same id already exists, it is disposed first.
22895
23208
  */
22896
23209
  async subscribe(sub) {
@@ -22901,9 +23214,16 @@ class WakerSubscriptionManager {
22901
23214
  throw new Error("WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options");
22902
23215
  }
22903
23216
  const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;
23217
+ if (sub.type === "mention" && sub.className && !sub.terms?.length) {
23218
+ // Without terms the whole-word check cannot run, and every substring
23219
+ // ("metadata" for "data") would wake the agent.
23220
+ throw new Error(`Waker subscription ${sub.id}: a mention subscription needs its terms (get_mention_waker_config returns them)`);
23221
+ }
22904
23222
  this.logger.info(`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`);
22905
- this.logger.info(`[waker] ${sub.id}: SPARQL query:\n${sub.query}`);
22906
- const proxy = new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
23223
+ this.logger.info(`[waker] ${sub.id}: ${sub.className ? `model query over ${sub.className}` : "SPARQL query"}:\n${sub.query}`);
23224
+ const proxy = sub.className
23225
+ ? new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient, sub.className)
23226
+ : new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
22907
23227
  // Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
22908
23228
  // rejects this promise internally when subscribe() fails, and if nobody catches
22909
23229
  // it before the next microtask it crashes the process.
@@ -22944,6 +23264,7 @@ class WakerSubscriptionManager {
22944
23264
  // reported as active or persisted as if it were.
22945
23265
  this.activeSubscriptions.delete(sub.id);
22946
23266
  this.seenMessages.delete(sub.id);
23267
+ this.delivered.delete(sub.id);
22947
23268
  this.persist();
22948
23269
  // Keep it pending and re-attempt: the usual cause (locked wallet, executor
22949
23270
  // mid-restart, a handshake the executor never answered) clears on its
@@ -22968,33 +23289,62 @@ class WakerSubscriptionManager {
22968
23289
  this.pendingSubscriptions.delete(sub.id);
22969
23290
  this.logger.info(`[waker] ${sub.id}: subscription initialized successfully`);
22970
23291
  // Seed from persisted seen messages so we don't re-wake after restart
23292
+ const restored = Object.prototype.hasOwnProperty.call(this.previousSeenMessages, sub.id);
22971
23293
  const seen = new Set(this.previousSeenMessages[sub.id] ?? []);
22972
23294
  this.seenMessages.set(sub.id, seen);
23295
+ this.delivered.set(sub.id, new Set(seen));
22973
23296
  if (seen.size > 0) {
22974
23297
  this.logger.info(`[waker] ${sub.id}: seeded ${seen.size} seen message(s) from persisted state`);
22975
23298
  }
22976
- proxy.onResult(async (result) => {
22977
- this.logger.info(`[waker] ${sub.id}: onResult fired — type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);
22978
- // Query engine can deliver non-array values (e.g. false) on disconnect/reconnect — ignore them
22979
- if (!Array.isArray(result)) {
22980
- this.logger.warn(`[waker] ${sub.id}: ignoring non-array result: ${JSON.stringify(result)}`);
23299
+ // `opening` is the result the subscription holds when it opens (`proxy.result`): `onResult`
23300
+ // only reports later changes, so this is the one chance to see what was written meanwhile.
23301
+ const handleResult = async (result, opening = false) => {
23302
+ 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)}`);
23303
+ // A model subscription delivers `{ instances }`, SPARQL an array of
23304
+ // rows. Anything else (e.g. `false` on a disconnect/reconnect) is
23305
+ // ignored.
23306
+ const rows = sub.className ? result?.instances : result;
23307
+ if (!Array.isArray(rows)) {
23308
+ this.logger.warn(`[waker] ${sub.id}: ignoring result without ${sub.className ? "instances" : "rows"}: ${JSON.stringify(result)}`);
22981
23309
  return;
22982
23310
  }
22983
23311
  if (sub.type === "mention") {
22984
- // For mention subscriptions: track seen message addresses.
22985
- // Only wake for messages we haven't seen before.
23312
+ // For mention subscriptions: track seen record ids.
23313
+ // Only wake for records we haven't seen before.
22986
23314
  const currentSeen = this.seenMessages.get(sub.id) ?? new Set();
22987
23315
  const newMessages = [];
22988
- for (const item of result) {
22989
- if (item && item.source && !currentSeen.has(item.source)) {
22990
- newMessages.push(item.source);
23316
+ const terms = sub.terms ?? [];
23317
+ for (const item of rows) {
23318
+ // A SPARQL row names the record as `source`, a model row as `id`.
23319
+ const address = sub.className ? item?.id : item?.source;
23320
+ if (typeof address !== "string" || !address || currentSeen.has(address))
23321
+ continue;
23322
+ if (terms.length) {
23323
+ // The mention query matched a substring; wake only on a whole word.
23324
+ const text = Array.isArray(item.text) ? item.text.join(" ") : item.text;
23325
+ if (typeof text !== "string" || !holdsAWholeWordTerm(text, terms)) {
23326
+ this.logger.debug(`[waker] ${sub.id}: ${address} holds no term as a whole word, skipping`);
23327
+ continue;
23328
+ }
22991
23329
  }
23330
+ currentSeen.add(address);
23331
+ newMessages.push(address);
22992
23332
  }
22993
23333
  if (newMessages.length === 0) {
22994
- this.logger.info(`[waker] ${sub.id}: all ${result.length} items already seen, skipping`);
23334
+ this.logger.info(`[waker] ${sub.id}: no new mention among ${rows.length} items, skipping`);
23335
+ return;
23336
+ }
23337
+ if (opening && !restored) {
23338
+ // A new subscription: what it opens on is history, readable on demand, not news.
23339
+ this.seenMessages.set(sub.id, currentSeen);
23340
+ const done = this.delivered.get(sub.id) ?? new Set();
23341
+ for (const address of newMessages)
23342
+ done.add(address);
23343
+ this.delivered.set(sub.id, done);
23344
+ this.logger.info(`[waker] ${sub.id}: ${newMessages.length} existing mention(s) taken as history, not woken`);
22995
23345
  return;
22996
23346
  }
22997
- this.logger.info(`[waker] ${sub.id}: ${newMessages.length} new message(s) out of ${result.length} total`);
23347
+ this.logger.info(`[waker] ${sub.id}: ${newMessages.length} new message(s) out of ${rows.length} total`);
22998
23348
  // Resolve parents, and the chain above them, per new message
22999
23349
  const mentions = [];
23000
23350
  for (const msgAddr of newMessages) {
@@ -23005,25 +23355,20 @@ class WakerSubscriptionManager {
23005
23355
  (ancestors.length ? `; ancestors: ${ancestors.join(", ")}` : ""));
23006
23356
  mentions.push({ address: msgAddr, parents, ancestors });
23007
23357
  }
23008
- // Mark all new messages as seen
23009
- for (const addr of newMessages) {
23010
- currentSeen.add(addr);
23011
- }
23012
23358
  this.seenMessages.set(sub.id, currentSeen);
23013
- // Debounce the wake callback
23014
- const existing = this.debounceTimers.get(sub.id);
23015
- if (existing)
23016
- clearTimeout(existing);
23017
- this.debounceTimers.set(sub.id, setTimeout(() => {
23018
- this.onWake(sub, result, mentions);
23019
- this.debounceTimers.delete(sub.id);
23020
- this.persist();
23021
- }, this.debounceMs));
23359
+ const pending = this.undelivered.get(sub.id) ?? new Map();
23360
+ for (const mention of mentions)
23361
+ pending.set(mention.address, mention);
23362
+ this.undelivered.set(sub.id, pending);
23363
+ this.scheduleMentionWake(sub, result, this.debounceMs);
23022
23364
  }
23023
23365
  else {
23366
+ // A container's contents when the subscription opens are not an update.
23367
+ if (opening)
23368
+ return;
23024
23369
  // For channel-messages: always notify the agent on every subscription push.
23025
23370
  // No deduplication — the agent reads recent messages itself.
23026
- this.logger.info(`[waker] ${sub.id}: channel update (${result.length} items)`);
23371
+ this.logger.info(`[waker] ${sub.id}: channel update (${rows.length} items)`);
23027
23372
  const existing = this.debounceTimers.get(sub.id);
23028
23373
  if (existing)
23029
23374
  clearTimeout(existing);
@@ -23032,7 +23377,8 @@ class WakerSubscriptionManager {
23032
23377
  this.debounceTimers.delete(sub.id);
23033
23378
  }, this.debounceMs));
23034
23379
  }
23035
- });
23380
+ };
23381
+ proxy.onResult((result) => handleResult(result));
23036
23382
  if (this.isStale(sub.id, token)) {
23037
23383
  try {
23038
23384
  proxy.dispose();
@@ -23042,6 +23388,16 @@ class WakerSubscriptionManager {
23042
23388
  }
23043
23389
  this.proxies.set(sub.id, proxy);
23044
23390
  this.activeSubscriptions.set(sub.id, sub);
23391
+ // After a restart this wakes on mentions written while the waker was down; on a new
23392
+ // subscription it records the existing ones as history.
23393
+ if (proxy.result !== undefined) {
23394
+ try {
23395
+ await handleResult(proxy.result, true);
23396
+ }
23397
+ catch (e) {
23398
+ this.logger.warn(`[waker] ${sub.id}: reading the opening result failed: ${e?.message ?? e}`);
23399
+ }
23400
+ }
23045
23401
  this.persist();
23046
23402
  this.logger.info(`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`);
23047
23403
  }
@@ -23117,9 +23473,61 @@ class WakerSubscriptionManager {
23117
23473
  this.activeSubscriptions.delete(id);
23118
23474
  this.pendingSubscriptions.delete(id);
23119
23475
  this.seenMessages.delete(id);
23476
+ this.delivered.delete(id);
23477
+ this.undelivered.delete(id);
23478
+ this.wakeFailures.delete(id);
23120
23479
  if (persist)
23121
23480
  this.persist();
23122
23481
  }
23482
+ /** (Re)start the timer that offers `sub`'s undelivered mentions to `onWake` after `delayMs`. */
23483
+ scheduleMentionWake(sub, result, delayMs) {
23484
+ const existing = this.debounceTimers.get(sub.id);
23485
+ if (existing)
23486
+ clearTimeout(existing);
23487
+ this.debounceTimers.set(sub.id, setTimeout(() => {
23488
+ this.debounceTimers.delete(sub.id);
23489
+ void this.deliverMentions(sub, result);
23490
+ }, delayMs));
23491
+ }
23492
+ /**
23493
+ * Offer every undelivered mention of `sub` in one wake. On delivery they join the persisted
23494
+ * seen set; on failure they stay undelivered and are offered again with backoff.
23495
+ */
23496
+ async deliverMentions(sub, result) {
23497
+ const pending = this.undelivered.get(sub.id);
23498
+ if (!pending?.size || !this.activeSubscriptions.has(sub.id))
23499
+ return;
23500
+ const mentions = Array.from(pending.values());
23501
+ let delivered;
23502
+ try {
23503
+ delivered = (await this.onWake(sub, result, mentions)) !== false;
23504
+ }
23505
+ catch (e) {
23506
+ this.logger.warn(`[waker] ${sub.id}: wake callback threw: ${e?.message ?? e}`);
23507
+ delivered = false;
23508
+ }
23509
+ // Disposed while the wake was in flight: nothing left to retry or persist.
23510
+ if (this.undelivered.get(sub.id) !== pending)
23511
+ return;
23512
+ if (!delivered) {
23513
+ const failures = (this.wakeFailures.get(sub.id) ?? 0) + 1;
23514
+ this.wakeFailures.set(sub.id, failures);
23515
+ const delay = Math.min(this.retryWakeMs * 2 ** (failures - 1), 60000);
23516
+ this.logger.warn(`[waker] ${sub.id}: wake for ${mentions.length} mention(s) not delivered, offering again in ${delay}ms`);
23517
+ // A newer result arriving meanwhile restarts the timer and joins this wake.
23518
+ if (!this.debounceTimers.has(sub.id))
23519
+ this.scheduleMentionWake(sub, result, delay);
23520
+ return;
23521
+ }
23522
+ this.wakeFailures.delete(sub.id);
23523
+ const done = this.delivered.get(sub.id) ?? new Set();
23524
+ for (const mention of mentions) {
23525
+ pending.delete(mention.address);
23526
+ done.add(mention.address);
23527
+ }
23528
+ this.delivered.set(sub.id, done);
23529
+ this.persist();
23530
+ }
23123
23531
  /** Dispose all active subscriptions and drop anything still pending. */
23124
23532
  disposeAll() {
23125
23533
  // Bump the epoch first: in-flight subscribe() calls have no proxy in the
@@ -23142,60 +23550,50 @@ class WakerSubscriptionManager {
23142
23550
  has(id) {
23143
23551
  return this.activeSubscriptions.has(id);
23144
23552
  }
23145
- /** Resolve one containment level in one query; skip unsafe IRI tokens and treat failures as none. */
23553
+ /**
23554
+ * Everything holding any of `addresses`, in one model query: a `Container`
23555
+ * step in (#1446). The executor follows `ad4m://has_child` on any node and
23556
+ * each class's own `children` relation on its instances, so the waker
23557
+ * looks up no predicate. Failures count as none.
23558
+ */
23146
23559
  async parentsOf(sub, addresses) {
23147
- const safe = [...new Set(addresses)].filter((address) => {
23148
- if (/[<>"{}|^`\\\s\x00-\x20]/.test(address)) {
23149
- this.logger.warn(`[waker] ${sub.id}: skipping parent lookup for unsafe address ${JSON.stringify(address)}`);
23150
- return false;
23151
- }
23152
- return true;
23153
- });
23154
- if (!safe.length)
23560
+ if (!addresses.length)
23155
23561
  return [];
23156
- try {
23157
- const query = safe.length === 1
23158
- ? `SELECT ?source WHERE { ?source <ad4m://has_child> <${safe[0]}> . }`
23159
- : `SELECT ?source WHERE { VALUES ?child { ${safe.map((address) => `<${address}>`).join(" ")} } ?source <ad4m://has_child> ?child . }`;
23160
- const rows = await this.perspectiveClient.querySparql(sub.perspective, query);
23161
- if (!Array.isArray(rows))
23162
- return [];
23163
- // A row omits a variable left unbound in its solution.
23164
- return rows.map((row) => row?.source).filter((source) => typeof source === "string");
23165
- }
23166
- catch (err) {
23167
- this.logger.warn(`[waker] ${sub.id}: parent resolution failed for ${JSON.stringify(safe)} — ${err?.message ?? err}`);
23168
- return [];
23169
- }
23562
+ return this.containers(sub, { ids: [...new Set(addresses)], direction: "in" }, addresses);
23170
23563
  }
23171
23564
  /**
23172
- * The chain above an item's parents, a level at a time, nearest first, up to `ancestorDepth`.
23173
- *
23174
- * Breadth-first with a visited set: containment is a graph, not a tree — an item can sit in two
23175
- * places, and nothing stops a cycle — so each address is reported once and the walk always ends.
23176
- * Each level uses one batched parent lookup, bounded by the depth.
23565
+ * The chain above an item's parents, nearest first, up to `ancestorDepth` levels: one
23566
+ * transitive `Container` walk in from the parents, bounded by `maxDepth`. The executor walks
23567
+ * containment as a graph, so each address comes once however many paths reach it, and a
23568
+ * cycle ends. The item and its parents are never reported as ancestors.
23177
23569
  */
23178
23570
  async ancestorsOf(sub, address, parents) {
23571
+ if (!parents.length || this.ancestorDepth <= 0)
23572
+ return [];
23573
+ const scope = { ids: parents, direction: "in", transitive: true, maxDepth: this.ancestorDepth };
23179
23574
  const seen = new Set([address, ...parents]);
23180
- const ancestors = [];
23181
- let level = parents;
23182
- for (let depth = 0; depth < this.ancestorDepth && level.length; depth++) {
23183
- const next = [];
23184
- for (const parent of await this.parentsOf(sub, level)) {
23185
- if (seen.has(parent))
23186
- continue;
23187
- seen.add(parent);
23188
- next.push(parent);
23189
- }
23190
- ancestors.push(...next);
23191
- level = next;
23575
+ return (await this.containers(sub, scope, parents)).filter((id) => !seen.has(id));
23576
+ }
23577
+ /** The ids of the `Container` rows `parent` scopes to, in the executor's order. */
23578
+ async containers(sub, parent, from) {
23579
+ try {
23580
+ const query = JSON.stringify({ parent, properties: [] });
23581
+ const result = await this.perspectiveClient.modelQuery(sub.perspective, CONTAINER, query);
23582
+ const instances = result?.instances;
23583
+ if (!Array.isArray(instances))
23584
+ return [];
23585
+ return instances.map((row) => row?.id).filter((id) => typeof id === "string");
23586
+ }
23587
+ catch (err) {
23588
+ this.logger.warn(`[waker] ${sub.id}: containment lookup failed for ${JSON.stringify(from)} — ${err?.message ?? err}`);
23589
+ return [];
23192
23590
  }
23193
- return ancestors;
23194
23591
  }
23195
23592
  persist() {
23196
23593
  if (this.onPersist) {
23197
23594
  const seen = {};
23198
- for (const [id, set] of this.seenMessages) {
23595
+ // Only what was delivered: anything else must wake again after a restart.
23596
+ for (const [id, set] of this.delivered) {
23199
23597
  seen[id] = Array.from(set);
23200
23598
  }
23201
23599
  this.onPersist(this.getActive(), seen);
@@ -23711,6 +24109,7 @@ exports.Literal = Literal;
23711
24109
  exports.LiveQuery = LiveQuery;
23712
24110
  exports.LocalModel = LocalModel;
23713
24111
  exports.LocalModelInput = LocalModelInput;
24112
+ exports.MENTION_TEXT_LIMIT = MENTION_TEXT_LIMIT;
23714
24113
  exports.MeshManager = MeshManager;
23715
24114
  exports.Model = Model$1;
23716
24115
  exports.ModelApi = ModelApi;
@@ -23793,9 +24192,12 @@ exports.getPropertyOption = getPropertyOption;
23793
24192
  exports.getRelationsMetadata = getRelationsMetadata;
23794
24193
  exports.hasJsOnlyWhereFilters = hasJsOnlyWhereFilters;
23795
24194
  exports.hintFor = hintFor;
24195
+ exports.holdsAWholeWordTerm = holdsAWholeWordTerm;
23796
24196
  exports.ifExpr = ifExpr;
23797
24197
  exports.invalidatePerspectiveCache = invalidatePerspectiveCache;
23798
24198
  exports.isArrayType = isArrayType;
24199
+ exports.isContainedScope = isContainedScope;
24200
+ exports.isContainmentTraversal = isContainmentTraversal;
23799
24201
  exports.isExpression = isExpression;
23800
24202
  exports.isIncludeProjection = isIncludeProjection;
23801
24203
  exports.isLink = isLink;