@coasys/ad4m 0.13.1-staging.3 → 0.13.1-staging.5

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 (100) hide show
  1. package/lib/index.cjs +414 -160
  2. package/lib/index.js +414 -161
  3. package/lib/src/agent/AgentClient.d.ts +16 -1
  4. package/lib/src/agent/AgentClient.js +21 -2
  5. package/lib/src/ai/AITypes.d.ts +6 -2
  6. package/lib/src/apiClient.js +1 -1
  7. package/lib/src/generated/api/AgentMessage.d.ts +10 -0
  8. package/lib/src/generated/api/AgentReply.d.ts +9 -0
  9. package/{src/generated/api/PerspectiveRemovedWithOwner.ts → lib/src/generated/api/AgentReply.js} +1 -2
  10. package/lib/src/generated/api/Apps.d.ts +4 -0
  11. package/lib/src/generated/api/Events.d.ts +10 -12
  12. package/lib/src/generated/api/FlowStateChangedEvent.d.ts +3 -2
  13. package/lib/src/generated/api/Model.d.ts +4 -0
  14. package/lib/src/generated/api/ModelApi.d.ts +5 -1
  15. package/lib/src/generated/api/ModelApiInput.d.ts +7 -1
  16. package/lib/src/generated/api/Notification.d.ts +5 -1
  17. package/lib/src/generated/api/NotificationInput.d.ts +4 -0
  18. package/lib/src/generated/api/PerspectiveEvent.d.ts +8 -0
  19. package/lib/src/generated/api/{PerspectiveLinkWithOwner.d.ts → PerspectiveLinkEvent.d.ts} +4 -2
  20. package/lib/src/generated/api/{PerspectiveLinkUpdatedWithOwner.d.ts → PerspectiveLinkUpdatedEvent.d.ts} +4 -2
  21. package/lib/src/generated/api/PerspectiveRemovedEvent.d.ts +7 -0
  22. package/lib/src/generated/api/PerspectiveRemovedEvent.js +2 -0
  23. package/lib/src/generated/api/RequestCapabilityRequest.d.ts +1 -0
  24. package/lib/src/generated/api/RpcMethods.d.ts +16 -1
  25. package/lib/src/generated/api/RpcMethods.js +1 -0
  26. package/lib/src/generated/api/RunAgentRequest.d.ts +26 -0
  27. package/lib/src/generated/api/RuntimeUpdateNotificationParams.d.ts +6 -1
  28. package/lib/src/generated/api/UsersRevokeAllSessionsParams.d.ts +7 -0
  29. package/lib/src/generated/api/UsersRevokeAllSessionsParams.js +2 -0
  30. package/lib/src/generated/api/index.d.ts +3 -0
  31. package/lib/src/index.d.ts +1 -0
  32. package/lib/src/index.js +1 -0
  33. package/lib/src/model/types.d.ts +6 -0
  34. package/lib/src/neighbourhood/SfuManager.d.ts +15 -0
  35. package/lib/src/neighbourhood/SfuManager.js +39 -2
  36. package/lib/src/perspectives/Mentioning.d.ts +37 -0
  37. package/lib/src/perspectives/Mentioning.js +58 -0
  38. package/lib/src/perspectives/PerspectiveClient.d.ts +22 -0
  39. package/lib/src/perspectives/PerspectiveClient.js +13 -0
  40. package/lib/src/perspectives/PerspectiveProxy.d.ts +19 -0
  41. package/lib/src/perspectives/PerspectiveProxy.js +19 -0
  42. package/lib/src/perspectives/TextContent.d.ts +4 -0
  43. package/lib/src/perspectives/TextContent.js +4 -0
  44. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +69 -10
  45. package/lib/src/perspectives/WakerSubscriptionManager.js +163 -61
  46. package/lib/src/runtime/RuntimeClient.d.ts +6 -3
  47. package/lib/src/runtime/RuntimeClient.js +2 -0
  48. package/lib/src/runtime/RuntimeTypes.d.ts +5 -1
  49. package/package.json +2 -2
  50. package/src/Ad4mClient.test.ts +53 -18
  51. package/src/agent/AgentClient.ts +26 -2
  52. package/src/ai/AITypes.ts +6 -2
  53. package/src/apiClient.test.ts +2 -3
  54. package/src/apiClient.ts +1 -1
  55. package/src/generated/api/AgentMessage.ts +10 -0
  56. package/src/generated/api/AgentReply.ts +10 -0
  57. package/src/generated/api/Apps.ts +6 -1
  58. package/src/generated/api/Events.ts +10 -12
  59. package/src/generated/api/FlowStateChangedEvent.ts +3 -2
  60. package/src/generated/api/Model.ts +4 -0
  61. package/src/generated/api/ModelApi.ts +5 -1
  62. package/src/generated/api/ModelApiInput.ts +8 -1
  63. package/src/generated/api/Notification.ts +5 -1
  64. package/src/generated/api/NotificationInput.ts +6 -1
  65. package/src/generated/api/PerspectiveEvent.ts +7 -0
  66. package/src/generated/api/{PerspectiveLinkUpdatedWithOwner.ts → PerspectiveLinkEvent.ts} +4 -1
  67. package/src/generated/api/PerspectiveLinkUpdatedEvent.ts +7 -0
  68. package/src/generated/api/PerspectiveRemovedEvent.ts +6 -0
  69. package/src/generated/api/RequestCapabilityRequest.ts +1 -1
  70. package/src/generated/api/RpcMethods.ts +8 -1
  71. package/src/generated/api/RunAgentRequest.ts +26 -0
  72. package/src/generated/api/RuntimeUpdateNotificationParams.ts +7 -1
  73. package/src/generated/api/UsersRevokeAllSessionsParams.ts +8 -0
  74. package/src/generated/api/index.ts +3 -0
  75. package/src/index.ts +1 -0
  76. package/src/model/types.ts +6 -0
  77. package/src/neighbourhood/SfuManager.test.ts +151 -2
  78. package/src/neighbourhood/SfuManager.ts +38 -1
  79. package/src/perspectives/Mentioning.test.ts +78 -0
  80. package/src/perspectives/Mentioning.ts +42 -0
  81. package/src/perspectives/PerspectiveClient.ts +30 -0
  82. package/src/perspectives/PerspectiveProxy.ts +26 -0
  83. package/src/perspectives/TextContent.ts +4 -0
  84. package/src/perspectives/WakerSubscriptionManager.test.ts +383 -151
  85. package/src/perspectives/WakerSubscriptionManager.ts +220 -61
  86. package/src/perspectives/link-updated-type.test.ts +2 -2
  87. package/src/perspectives/listener-leaks.test.ts +3 -3
  88. package/src/runtime/RuntimeClient.ts +6 -3
  89. package/src/runtime/RuntimeTypes.ts +8 -1
  90. package/lib/src/generated/api/MessageReceivedEvent.d.ts +0 -7
  91. package/lib/src/generated/api/PerspectiveRemovedWithOwner.d.ts +0 -5
  92. package/lib/src/generated/api/PerspectiveWithOwner.d.ts +0 -6
  93. package/src/generated/api/MessageReceivedEvent.ts +0 -7
  94. package/src/generated/api/PerspectiveLinkWithOwner.ts +0 -4
  95. package/src/generated/api/PerspectiveWithOwner.ts +0 -4
  96. /package/lib/src/generated/api/{PerspectiveRemovedWithOwner.js → AgentMessage.js} +0 -0
  97. /package/lib/src/generated/api/{MessageReceivedEvent.js → PerspectiveEvent.js} +0 -0
  98. /package/lib/src/generated/api/{PerspectiveLinkUpdatedWithOwner.js → PerspectiveLinkEvent.js} +0 -0
  99. /package/lib/src/generated/api/{PerspectiveLinkWithOwner.js → PerspectiveLinkUpdatedEvent.js} +0 -0
  100. /package/lib/src/generated/api/{PerspectiveWithOwner.js → RunAgentRequest.js} +0 -0
package/lib/index.cjs CHANGED
@@ -109,6 +109,7 @@ const LONG_METHODS = new Set([
109
109
  "language.publish",
110
110
  "neighbourhood.join",
111
111
  "neighbourhood.publish",
112
+ "perspective.runAgent",
112
113
  "perspective.runInterpretation",
113
114
  "perspective.runInterpretationWithHarness",
114
115
  "runtime.restartHolochain",
@@ -212,7 +213,7 @@ class ApiClient {
212
213
  ? new RpcError(401, event.reason || 'token expired or revoked')
213
214
  : closedError(event?.code === CLOSE_TRY_AGAIN_LATER ? event.reason : undefined));
214
215
  if (event?.code === CLOSE_AUTH_FAILED && this._ws === ws) {
215
- this._failAuth(event.reason || 'token expired or revoked');
216
+ this._failAuth(event.reason || 'Unauthorized access: the token expired or was revoked');
216
217
  }
217
218
  else {
218
219
  this._onClose(ws, event?.code === CLOSE_TRY_AGAIN_LATER ? event.reason : undefined);
@@ -1296,8 +1297,15 @@ class AgentClient {
1296
1297
  async entanglementProofPreFlight(deviceKey, deviceKeyType) {
1297
1298
  return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('agent.entanglementProofPreflight', { deviceKey, deviceKeyType });
1298
1299
  }
1299
- async requestCapability(authInfo) {
1300
- return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('agent.requestCapability', { authInfo });
1300
+ /**
1301
+ * Asks the executor for a capability token. `agent` names the agent the token will act
1302
+ * as: a managed user's email or an agent's DID; absent, the executor's main agent. That
1303
+ * agent's owner approves the request (the operator for the main agent, the user for
1304
+ * theirs). Returns the request id that {@link generateJwt} redeems with the approver's
1305
+ * six-digit code.
1306
+ */
1307
+ async requestCapability(authInfo, agent) {
1308
+ return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('agent.requestCapability', agent === undefined ? { authInfo } : { authInfo, agent });
1301
1309
  }
1302
1310
  async permitCapability(auth) {
1303
1311
  return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('agent.permitCapability', { auth });
@@ -1333,6 +1341,18 @@ class AgentClient {
1333
1341
  async verifyEmailCode(email, code, verificationType) {
1334
1342
  return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('user.verifyEmail', { email, code, verificationType });
1335
1343
  }
1344
+ /** Revokes this client's user token. The executor then closes the client's sockets. */
1345
+ async logout() {
1346
+ return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('user.logout', {});
1347
+ }
1348
+ /**
1349
+ * Revokes every token of a user issued up to now, this client's own included, and closes
1350
+ * their sockets. A user leaves out `email` (or names themselves); the operator names the
1351
+ * user. Needs AGENT_UPDATE, which a login holds. Tokens from a later login work.
1352
+ */
1353
+ async revokeAllSessions(email) {
1354
+ return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('user.revokeAllSessions', email === undefined ? {} : { email });
1355
+ }
1336
1356
  // Hosting methods
1337
1357
  async hostingUserInfo() {
1338
1358
  const info = (await __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('hosting.info', {})).userInfo ?? {
@@ -1826,6 +1846,8 @@ class SfuManager {
1826
1846
  this.rosterUnsubscribe = null;
1827
1847
  this.dataChannelUnsubscribe = null;
1828
1848
  this.disconnectedTimer = null;
1849
+ /** Running while the room's roster leaves this agent out: see `noticeRoster`. */
1850
+ this.unlistedTimer = null;
1829
1851
  this.neighbourhood = neighbourhood;
1830
1852
  this.neighbourhoodUrl = neighbourhoodUrl || "";
1831
1853
  this.roomId = roomId;
@@ -2112,6 +2134,37 @@ class SfuManager {
2112
2134
  this.renegotiationUnsubscribe = null;
2113
2135
  this.rosterUnsubscribe?.();
2114
2136
  this.rosterUnsubscribe = null;
2137
+ this.clearUnlistedTimer();
2138
+ }
2139
+ clearUnlistedTimer() {
2140
+ if (this.unlistedTimer) {
2141
+ clearTimeout(this.unlistedTimer);
2142
+ this.unlistedTimer = null;
2143
+ }
2144
+ }
2145
+ /**
2146
+ * The room's roster no longer lists this agent while `pc` is the call's:
2147
+ * the server has dropped this session, and ICE may not say so. In E6
2148
+ * (CI job 53158) one of six sessions never started a rebuild after a
2149
+ * 20 s outage the server had dropped it for. Rebuild once the roster has
2150
+ * left this agent out for `UNLISTED_GRACE_MS`; a roster that lists it
2151
+ * again in that time cancels, since one published just before this
2152
+ * join landed can arrive after it.
2153
+ */
2154
+ noticeRoster(pc, dids) {
2155
+ if (dids.includes(this.agentDid)) {
2156
+ this.clearUnlistedTimer();
2157
+ return;
2158
+ }
2159
+ if (this.unlistedTimer)
2160
+ return;
2161
+ this.unlistedTimer = setTimeout(() => {
2162
+ this.unlistedTimer = null;
2163
+ if (this.state.peerConnection !== pc)
2164
+ return;
2165
+ console.info("SFU: the room no longer lists this session, rebuilding the call");
2166
+ void this.reconnect();
2167
+ }, SfuManager.UNLISTED_GRACE_MS);
2115
2168
  }
2116
2169
  /** Undo a join that failed part way: its subscription and its connection. */
2117
2170
  abandon(pc) {
@@ -2146,8 +2199,10 @@ class SfuManager {
2146
2199
  if (!ours(roster) || this.state.peerConnection !== pc)
2147
2200
  return;
2148
2201
  void joined.then(() => {
2149
- if (this.state.peerConnection === pc)
2150
- this.applyRoster(roster.participants, true);
2202
+ if (this.state.peerConnection !== pc)
2203
+ return;
2204
+ this.applyRoster(roster.participants, true);
2205
+ this.noticeRoster(pc, roster.participants);
2151
2206
  });
2152
2207
  });
2153
2208
  for (const unsubscribe of previous)
@@ -2361,6 +2416,8 @@ SfuManager.MAX_RECONNECTS = 3;
2361
2416
  SfuManager.REJOIN_WINDOW_MS = 120000;
2362
2417
  /** How long ICE may stay disconnected before a rebuild: the executor's `ICE_DISCONNECT_GRACE`. */
2363
2418
  SfuManager.DISCONNECT_GRACE_MS = 10000;
2419
+ /** How long the roster may leave this agent out before the call is rebuilt. */
2420
+ SfuManager.UNLISTED_GRACE_MS = 3000;
2364
2421
 
2365
2422
  /**
2366
2423
  * Peer-to-peer WebRTC mesh transport for the AD4M SDK Session interface.
@@ -7864,6 +7921,19 @@ class PerspectiveProxy {
7864
7921
  observationId, emitDebugEvents, options) {
7865
7922
  return await __classPrivateFieldGet$6(this, _PerspectiveProxy_client, "f").runInterpretationWithHarness(__classPrivateFieldGet$6(this, _PerspectiveProxy_handle, "f").uuid, transcript, basePrefix, maxToolCalls, classes, modelOverride, undefined, observationId, emitDebugEvents, options);
7866
7923
  }
7924
+ /**
7925
+ * Ask a model something about this perspective, or ask it to change something, with the
7926
+ * executor's own tools — including the tools apps install for their records. It reads freely;
7927
+ * it writes only with the tools named in `settings.writeTools`, as you. Answers with the
7928
+ * model's final reply.
7929
+ *
7930
+ * @param messages the conversation so far, the person's request last
7931
+ * @param settings `context` (what the person is looking at), `writeTools`, `model`, `maxToolCalls`
7932
+ * @param options `signal` / `timeoutMs` (default {@link LONG_TIMEOUT_MS})
7933
+ */
7934
+ async runAgent(messages, settings, options) {
7935
+ return await __classPrivateFieldGet$6(this, _PerspectiveProxy_client, "f").runAgent(__classPrivateFieldGet$6(this, _PerspectiveProxy_handle, "f").uuid, messages, settings, options);
7936
+ }
7867
7937
  /**
7868
7938
  * Register a neighbourhood auto-processor on this perspective. The executor
7869
7939
  * then runs interpretation automatically over new source items (like Flux
@@ -8238,6 +8308,12 @@ class PerspectiveProxy {
8238
8308
  /**
8239
8309
  * Adds a pre-signed LinkExpression to the perspective.
8240
8310
  *
8311
+ * The executor checks the signature against `link.author` and stores the
8312
+ * verdict as `proof.valid`. If the same link (author, source, predicate,
8313
+ * target and timestamp) is already stored with a signature that verifies,
8314
+ * its stored proof is kept. The expression passed here is still returned
8315
+ * and, when Shared, committed to the neighbourhood as given.
8316
+ *
8241
8317
  * @param link - The signed LinkExpression to add
8242
8318
  * @param status - Whether the link should be shared
8243
8319
  * @param batchId - Optional batch ID to group this operation with others
@@ -9754,6 +9830,19 @@ class PerspectiveClient {
9754
9830
  emitDebugEvents,
9755
9831
  }, options);
9756
9832
  }
9833
+ /**
9834
+ * A conversation with a model in this perspective, using the executor's own tools: the tools
9835
+ * that read this perspective, and only the writing tools named in `writeTools`. Every tool a
9836
+ * session offers acts on this perspective alone, so tools about other perspectives, the agent
9837
+ * or the node (listing or publishing perspectives, the profile) are not available. Runs as the
9838
+ * caller, with the caller's capabilities, and answers with the model's final reply.
9839
+ *
9840
+ * Defaults to {@link LONG_TIMEOUT_MS}: an agent may read documentation and make many tool
9841
+ * calls before it answers.
9842
+ */
9843
+ async runAgent(uuid, messages, settings, options) {
9844
+ return __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call('perspective.runAgent', { uuid, messages, ...settings }, options);
9845
+ }
9757
9846
  /**
9758
9847
  * Register a neighbourhood auto-processor on this perspective. The executor's
9759
9848
  * watch loop then runs interpretation automatically over new source items
@@ -9972,6 +10061,8 @@ class RuntimeClient {
9972
10061
  async removeKnownLinkLanguageTemplates(addresses) {
9973
10062
  return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, "f").call('runtime.removeLinkLanguageTemplates', { addresses });
9974
10063
  }
10064
+ /** Every link-language template the executor knows, with its meta (name, description,
10065
+ * `possibleTemplateParams`). A template whose meta cannot be read is left out. */
9975
10066
  async knownLinkLanguageTemplates() {
9976
10067
  return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, "f").call('runtime.linkLanguageTemplates', {});
9977
10068
  }
@@ -21818,13 +21909,13 @@ class LanguageLanguageInput {
21818
21909
  * const runs = await InterpretationRun.findAll(perspective);
21819
21910
  * const configs = await AutoProcessorConfig.findAll(perspective);
21820
21911
  */
21821
- var __decorate$3 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
21912
+ var __decorate$4 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
21822
21913
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
21823
21914
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21824
21915
  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;
21825
21916
  return c > 3 && r && Object.defineProperty(target, key, r), r;
21826
21917
  };
21827
- var __metadata$3 = (undefined && undefined.__metadata) || function (k, v) {
21918
+ var __metadata$4 = (undefined && undefined.__metadata) || function (k, v) {
21828
21919
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
21829
21920
  };
21830
21921
  // ── AutoProcessorConfig ─────────────────────────────────────────────────────
@@ -21865,71 +21956,71 @@ exports.AutoProcessorConfig = class AutoProcessorConfig extends Ad4mModel {
21865
21956
  // `batchMax` + `claimTtlMs` — the Rust SDNA takes the same shape.
21866
21957
  }
21867
21958
  };
21868
- __decorate$3([
21959
+ __decorate$4([
21869
21960
  Property({ through: "ad4m://processor_id", required: true, identity: true }),
21870
- __metadata$3("design:type", String)
21961
+ __metadata$4("design:type", String)
21871
21962
  ], exports.AutoProcessorConfig.prototype, "processorId", void 0);
21872
- __decorate$3([
21963
+ __decorate$4([
21873
21964
  Property({ through: "ad4m://source_scope_query", required: true }),
21874
- __metadata$3("design:type", String)
21965
+ __metadata$4("design:type", String)
21875
21966
  ], exports.AutoProcessorConfig.prototype, "sourceScopeQuery", void 0);
21876
- __decorate$3([
21967
+ __decorate$4([
21877
21968
  Optional({ through: "ad4m://base_prefix" }),
21878
- __metadata$3("design:type", String)
21969
+ __metadata$4("design:type", String)
21879
21970
  ], exports.AutoProcessorConfig.prototype, "basePrefix", void 0);
21880
- __decorate$3([
21971
+ __decorate$4([
21881
21972
  HasMany({ through: "ad4m://interpretation_class", datatype: "xsd:string" }),
21882
- __metadata$3("design:type", Array)
21973
+ __metadata$4("design:type", Array)
21883
21974
  ], exports.AutoProcessorConfig.prototype, "interpretationClasses", void 0);
21884
- __decorate$3([
21975
+ __decorate$4([
21885
21976
  HasMany({ through: "ad4m://flow", datatype: "xsd:string" }),
21886
- __metadata$3("design:type", Array)
21977
+ __metadata$4("design:type", Array)
21887
21978
  ], exports.AutoProcessorConfig.prototype, "flows", void 0);
21888
- __decorate$3([
21979
+ __decorate$4([
21889
21980
  Property({ through: "ad4m://debounce_ms", required: true }),
21890
- __metadata$3("design:type", String)
21981
+ __metadata$4("design:type", String)
21891
21982
  ], exports.AutoProcessorConfig.prototype, "debounceMs", void 0);
21892
- __decorate$3([
21983
+ __decorate$4([
21893
21984
  Optional({ through: "ad4m://batch_min" }),
21894
- __metadata$3("design:type", String)
21985
+ __metadata$4("design:type", String)
21895
21986
  ], exports.AutoProcessorConfig.prototype, "batchMin", void 0);
21896
- __decorate$3([
21987
+ __decorate$4([
21897
21988
  Property({ through: "ad4m://batch_max", required: true }),
21898
- __metadata$3("design:type", String)
21989
+ __metadata$4("design:type", String)
21899
21990
  ], exports.AutoProcessorConfig.prototype, "batchMax", void 0);
21900
- __decorate$3([
21991
+ __decorate$4([
21901
21992
  Optional({ through: "ad4m://max_wait_ms" }),
21902
- __metadata$3("design:type", String)
21993
+ __metadata$4("design:type", String)
21903
21994
  ], exports.AutoProcessorConfig.prototype, "maxWaitMs", void 0);
21904
- __decorate$3([
21995
+ __decorate$4([
21905
21996
  Property({ through: "ad4m://claim_ttl_ms", required: true }),
21906
- __metadata$3("design:type", String)
21997
+ __metadata$4("design:type", String)
21907
21998
  ], exports.AutoProcessorConfig.prototype, "claimTtlMs", void 0);
21908
- __decorate$3([
21999
+ __decorate$4([
21909
22000
  Optional({ through: "ad4m://source_window_ms" }),
21910
- __metadata$3("design:type", String)
22001
+ __metadata$4("design:type", String)
21911
22002
  ], exports.AutoProcessorConfig.prototype, "sourceWindowMs", void 0);
21912
- __decorate$3([
22003
+ __decorate$4([
21913
22004
  Optional({ through: "ad4m://dedup_strategy" }),
21914
- __metadata$3("design:type", String)
22005
+ __metadata$4("design:type", String)
21915
22006
  ], exports.AutoProcessorConfig.prototype, "dedupStrategy", void 0);
21916
- __decorate$3([
22007
+ __decorate$4([
21917
22008
  Optional({ through: "ad4m://existing_scope" }),
21918
- __metadata$3("design:type", String)
22009
+ __metadata$4("design:type", String)
21919
22010
  ], exports.AutoProcessorConfig.prototype, "existingScope", void 0);
21920
- __decorate$3([
22011
+ __decorate$4([
21921
22012
  Optional({ through: "ad4m://mint_scope" }),
21922
- __metadata$3("design:type", String)
22013
+ __metadata$4("design:type", String)
21923
22014
  ], exports.AutoProcessorConfig.prototype, "mintScope", void 0);
21924
- __decorate$3([
22015
+ __decorate$4([
21925
22016
  Optional({ through: "ad4m://max_tool_calls" }),
21926
- __metadata$3("design:type", String)
22017
+ __metadata$4("design:type", String)
21927
22018
  ], exports.AutoProcessorConfig.prototype, "maxToolCalls", void 0);
21928
- __decorate$3([
22019
+ __decorate$4([
21929
22020
  Optional({ through: "ad4m://emit_debug_events", resolveLanguage: "literal" }),
21930
- __metadata$3("design:type", String)
22021
+ __metadata$4("design:type", String)
21931
22022
  ], exports.AutoProcessorConfig.prototype, "emitDebugEvents", void 0);
21932
- exports.AutoProcessorConfig = __decorate$3([
22023
+ exports.AutoProcessorConfig = __decorate$4([
21933
22024
  Model$1({ name: "AutoProcessor" })
21934
22025
  ], exports.AutoProcessorConfig);
21935
22026
  // ── InterpretationRun ───────────────────────────────────────────────────────
@@ -21953,39 +22044,39 @@ exports.InterpretationRun = class InterpretationRun extends Ad4mModel {
21953
22044
  this.sources = [];
21954
22045
  }
21955
22046
  };
21956
- __decorate$3([
22047
+ __decorate$4([
21957
22048
  Property({ through: "ad4m://interp/run_id", required: true, identity: true }),
21958
- __metadata$3("design:type", String)
22049
+ __metadata$4("design:type", String)
21959
22050
  ], exports.InterpretationRun.prototype, "runId", void 0);
21960
- __decorate$3([
22051
+ __decorate$4([
21961
22052
  Optional({ through: "ad4m://interp/model" }),
21962
- __metadata$3("design:type", String)
22053
+ __metadata$4("design:type", String)
21963
22054
  ], exports.InterpretationRun.prototype, "model", void 0);
21964
- __decorate$3([
22055
+ __decorate$4([
21965
22056
  Optional({ through: "ad4m://interp/prompt_version" }),
21966
- __metadata$3("design:type", String)
22057
+ __metadata$4("design:type", String)
21967
22058
  ], exports.InterpretationRun.prototype, "promptVersion", void 0);
21968
- __decorate$3([
22059
+ __decorate$4([
21969
22060
  Optional({ through: "ad4m://interp/ran_at" }),
21970
- __metadata$3("design:type", String)
22061
+ __metadata$4("design:type", String)
21971
22062
  ], exports.InterpretationRun.prototype, "ranAt", void 0);
21972
- __decorate$3([
22063
+ __decorate$4([
21973
22064
  Optional({ through: "ad4m://interp/processor" }),
21974
- __metadata$3("design:type", String)
22065
+ __metadata$4("design:type", String)
21975
22066
  ], exports.InterpretationRun.prototype, "processor", void 0);
21976
- __decorate$3([
22067
+ __decorate$4([
21977
22068
  HasMany({ through: "ad4m://interp/sources", datatype: "xsd:string" }),
21978
- __metadata$3("design:type", Array)
22069
+ __metadata$4("design:type", Array)
21979
22070
  ], exports.InterpretationRun.prototype, "sources", void 0);
21980
- __decorate$3([
22071
+ __decorate$4([
21981
22072
  Optional({ through: "ad4m://interp/debug_prompt", resolveLanguage: "literal" }),
21982
- __metadata$3("design:type", String)
22073
+ __metadata$4("design:type", String)
21983
22074
  ], exports.InterpretationRun.prototype, "debugPrompt", void 0);
21984
- __decorate$3([
22075
+ __decorate$4([
21985
22076
  Optional({ through: "ad4m://interp/debug_response", resolveLanguage: "literal" }),
21986
- __metadata$3("design:type", String)
22077
+ __metadata$4("design:type", String)
21987
22078
  ], exports.InterpretationRun.prototype, "debugResponse", void 0);
21988
- exports.InterpretationRun = __decorate$3([
22079
+ exports.InterpretationRun = __decorate$4([
21989
22080
  Model$1({ name: "InterpretationRun" })
21990
22081
  ], exports.InterpretationRun);
21991
22082
  // ── InterpretationOverlay ───────────────────────────────────────────────────
@@ -22015,15 +22106,15 @@ exports.InterpretationOverlay = class InterpretationOverlay extends Ad4mModel {
22015
22106
  this.kind = "";
22016
22107
  }
22017
22108
  };
22018
- __decorate$3([
22109
+ __decorate$4([
22019
22110
  Property({ through: "ad4m://interp/kind", required: true }),
22020
- __metadata$3("design:type", String)
22111
+ __metadata$4("design:type", String)
22021
22112
  ], exports.InterpretationOverlay.prototype, "kind", void 0);
22022
- __decorate$3([
22113
+ __decorate$4([
22023
22114
  Optional({ through: "ad4m://interp/run" }),
22024
- __metadata$3("design:type", String)
22115
+ __metadata$4("design:type", String)
22025
22116
  ], exports.InterpretationOverlay.prototype, "run", void 0);
22026
- exports.InterpretationOverlay = __decorate$3([
22117
+ exports.InterpretationOverlay = __decorate$4([
22027
22118
  Model$1({ name: "InterpretationOverlay" })
22028
22119
  ], exports.InterpretationOverlay);
22029
22120
 
@@ -22047,13 +22138,13 @@ exports.InterpretationOverlay = __decorate$3([
22047
22138
  * - the SDNA-parity test locks TS/Rust drift against
22048
22139
  * `rust-executor/src/perspectives/hardwired_sdna/flow_transition_proposal.json`.
22049
22140
  */
22050
- var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22141
+ var __decorate$3 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22051
22142
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22052
22143
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22053
22144
  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;
22054
22145
  return c > 3 && r && Object.defineProperty(target, key, r), r;
22055
22146
  };
22056
- var __metadata$2 = (undefined && undefined.__metadata) || function (k, v) {
22147
+ var __metadata$3 = (undefined && undefined.__metadata) || function (k, v) {
22057
22148
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22058
22149
  };
22059
22150
  /**
@@ -22160,55 +22251,55 @@ exports.FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel
22160
22251
  // of the proposal's own links (all written together during create_subject).
22161
22252
  }
22162
22253
  };
22163
- __decorate$2([
22254
+ __decorate$3([
22164
22255
  Property({ through: "ad4m://flow/instance", required: true, identity: true }),
22165
- __metadata$2("design:type", String)
22256
+ __metadata$3("design:type", String)
22166
22257
  ], exports.FlowTransitionProposal.prototype, "flowInstance", void 0);
22167
- __decorate$2([
22258
+ __decorate$3([
22168
22259
  Property({ through: "ad4m://flow/from_state", required: true }),
22169
- __metadata$2("design:type", String)
22260
+ __metadata$3("design:type", String)
22170
22261
  ], exports.FlowTransitionProposal.prototype, "fromState", void 0);
22171
- __decorate$2([
22262
+ __decorate$3([
22172
22263
  Property({ through: "ad4m://flow/to_state", required: true }),
22173
- __metadata$2("design:type", String)
22264
+ __metadata$3("design:type", String)
22174
22265
  ], exports.FlowTransitionProposal.prototype, "toState", void 0);
22175
- __decorate$2([
22266
+ __decorate$3([
22176
22267
  Property({ through: "ad4m://flow/proposer", required: true, getter: PROPOSER_GETTER, datatype: "xsd:string" }),
22177
- __metadata$2("design:type", String)
22268
+ __metadata$3("design:type", String)
22178
22269
  ], exports.FlowTransitionProposal.prototype, "proposer", void 0);
22179
- __decorate$2([
22270
+ __decorate$3([
22180
22271
  HasMany({ through: "ad4m://flow/evidence", datatype: "xsd:string" }),
22181
- __metadata$2("design:type", Array)
22272
+ __metadata$3("design:type", Array)
22182
22273
  ], exports.FlowTransitionProposal.prototype, "evidence", void 0);
22183
- __decorate$2([
22274
+ __decorate$3([
22184
22275
  Property({ through: "ad4m://flow/evidence_hashes", required: true }),
22185
- __metadata$2("design:type", String)
22276
+ __metadata$3("design:type", String)
22186
22277
  ], exports.FlowTransitionProposal.prototype, "evidenceHashes", void 0);
22187
- __decorate$2([
22278
+ __decorate$3([
22188
22279
  HasMany({ through: "ad4m://flow/output", datatype: "xsd:string" }),
22189
- __metadata$2("design:type", Array)
22280
+ __metadata$3("design:type", Array)
22190
22281
  ], exports.FlowTransitionProposal.prototype, "outputs", void 0);
22191
- __decorate$2([
22282
+ __decorate$3([
22192
22283
  Property({ through: "ad4m://flow/outputs_hash" }),
22193
- __metadata$2("design:type", String)
22284
+ __metadata$3("design:type", String)
22194
22285
  ], exports.FlowTransitionProposal.prototype, "outputsHash", void 0);
22195
- __decorate$2([
22286
+ __decorate$3([
22196
22287
  Property({ through: "ad4m://flow/nonce" }),
22197
- __metadata$2("design:type", String)
22288
+ __metadata$3("design:type", String)
22198
22289
  ], exports.FlowTransitionProposal.prototype, "nonce", void 0);
22199
- __decorate$2([
22290
+ __decorate$3([
22200
22291
  Optional({ through: "ad4m://flow/run_uri" }),
22201
- __metadata$2("design:type", String)
22292
+ __metadata$3("design:type", String)
22202
22293
  ], exports.FlowTransitionProposal.prototype, "runUri", void 0);
22203
- __decorate$2([
22294
+ __decorate$3([
22204
22295
  Optional({ through: "ad4m://flow/rationale" }),
22205
- __metadata$2("design:type", String)
22296
+ __metadata$3("design:type", String)
22206
22297
  ], exports.FlowTransitionProposal.prototype, "rationale", void 0);
22207
- __decorate$2([
22298
+ __decorate$3([
22208
22299
  HasMany({ through: "ad4m://acceptedBy", getter: ACCEPTED_BY_GETTER, readOnly: true }),
22209
- __metadata$2("design:type", Array)
22300
+ __metadata$3("design:type", Array)
22210
22301
  ], exports.FlowTransitionProposal.prototype, "acceptedBy", void 0);
22211
- exports.FlowTransitionProposal = __decorate$2([
22302
+ exports.FlowTransitionProposal = __decorate$3([
22212
22303
  Model$1({ name: "FlowTransitionProposal" })
22213
22304
  ], exports.FlowTransitionProposal);
22214
22305
  // ── FlowInstanceRecord ──────────────────────────────────────────────────────
@@ -22268,25 +22359,25 @@ exports.FlowInstanceRecord = class FlowInstanceRecord extends Ad4mModel {
22268
22359
  // of the instance's own links (all written together during `mint_flow_instance`).
22269
22360
  }
22270
22361
  };
22271
- __decorate$2([
22362
+ __decorate$3([
22272
22363
  Property({ through: "ad4m://flow/flow_uri", required: true, identity: true }),
22273
- __metadata$2("design:type", String)
22364
+ __metadata$3("design:type", String)
22274
22365
  ], exports.FlowInstanceRecord.prototype, "flowUri", void 0);
22275
- __decorate$2([
22366
+ __decorate$3([
22276
22367
  Property({ through: "ad4m://flow/base", required: true }),
22277
- __metadata$2("design:type", String)
22368
+ __metadata$3("design:type", String)
22278
22369
  ], exports.FlowInstanceRecord.prototype, "subject", void 0);
22279
- exports.FlowInstanceRecord = __decorate$2([
22370
+ exports.FlowInstanceRecord = __decorate$3([
22280
22371
  Model$1({ name: "FlowInstance" })
22281
22372
  ], exports.FlowInstanceRecord);
22282
22373
 
22283
- var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22374
+ var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22284
22375
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22285
22376
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22286
22377
  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;
22287
22378
  return c > 3 && r && Object.defineProperty(target, key, r), r;
22288
22379
  };
22289
- var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22380
+ var __metadata$2 = (undefined && undefined.__metadata) || function (k, v) {
22290
22381
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22291
22382
  };
22292
22383
  /**
@@ -22312,6 +22403,10 @@ var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22312
22403
  * reads it by its URI, `ad4m://TextContent`, so a perspective never stores it
22313
22404
  * and an app class named `TextContent` does not replace it. `register()` on
22314
22405
  * it writes nothing.
22406
+ *
22407
+ * The waker's mention subscription (`get_mention_waker_config`) reads it for
22408
+ * the agent's names in the text. Mention links it reads through
22409
+ * {@link Mentioning}, with text or without.
22315
22410
  */
22316
22411
  exports.TextContent = class TextContent extends Ad4mModel {
22317
22412
  constructor() {
@@ -22322,14 +22417,70 @@ exports.TextContent = class TextContent extends Ad4mModel {
22322
22417
  };
22323
22418
  /** The URI the executor reads it by. */
22324
22419
  exports.TextContent.builtinUri = "ad4m://TextContent";
22325
- __decorate$1([
22420
+ __decorate$2([
22326
22421
  Property({ through: "ad4m://text" }),
22327
- __metadata$1("design:type", String)
22422
+ __metadata$2("design:type", String)
22328
22423
  ], exports.TextContent.prototype, "text", void 0);
22329
- exports.TextContent = __decorate$1([
22424
+ exports.TextContent = __decorate$2([
22330
22425
  Model$1({ name: "TextContent", abstract: true })
22331
22426
  ], exports.TextContent);
22332
22427
 
22428
+ var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22429
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22430
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22431
+ 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;
22432
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
22433
+ };
22434
+ var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22435
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22436
+ };
22437
+ /**
22438
+ * The built-in abstract class `Mentioning { mentions }`: a record that
22439
+ * mentions agents — a post, a message, a block of a document. `mentions` is
22440
+ * a relation to their DIDs.
22441
+ *
22442
+ * Querying it reads every class that has a relation named `mentions`, or one
22443
+ * aliased to `mentions`, under any predicate, whether or not the class has
22444
+ * text. A class whose relation has another name aliases it:
22445
+ *
22446
+ * ```typescript
22447
+ * @Model({ name: "Note", implements: [Mentioning] })
22448
+ * class Note extends Ad4mModel {
22449
+ * @HasMany({ through: "app://cc", alias: { Mentioning: "mentions" } })
22450
+ * cc: string[] = [];
22451
+ * }
22452
+ *
22453
+ * const mentioningMe = await Mentioning.findAll(perspective, { where: { mentions: myDid } });
22454
+ * ```
22455
+ *
22456
+ * The waker's mention subscription (`get_mention_waker_config`) reads it: a
22457
+ * record whose `mentions` links the agent's DID, in a link another agent
22458
+ * wrote, wakes the agent whatever its text says. Names in text it reads
22459
+ * through {@link TextContent}.
22460
+ *
22461
+ * Built in: the executor declares it (mirrors
22462
+ * `rust-executor/src/perspectives/hardwired_sdna/mentioning.json`) and reads
22463
+ * it by its URI, `ad4m://Mentioning`, so a perspective never stores it and an
22464
+ * app class named `Mentioning` does not replace it. `register()` on it writes
22465
+ * nothing.
22466
+ */
22467
+ exports.Mentioning = class Mentioning extends Ad4mModel {
22468
+ constructor() {
22469
+ super(...arguments);
22470
+ /** The agents (DIDs) the record mentions. */
22471
+ this.mentions = [];
22472
+ }
22473
+ };
22474
+ /** The URI the executor reads it by. */
22475
+ exports.Mentioning.builtinUri = "ad4m://Mentioning";
22476
+ __decorate$1([
22477
+ HasMany({ through: "ad4m://mentions" }),
22478
+ __metadata$1("design:type", Array)
22479
+ ], exports.Mentioning.prototype, "mentions", void 0);
22480
+ exports.Mentioning = __decorate$1([
22481
+ Model$1({ name: "Mentioning", abstract: true })
22482
+ ], exports.Mentioning);
22483
+
22333
22484
  var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22334
22485
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22335
22486
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -22978,6 +23129,9 @@ function parseLitBoolean(val) {
22978
23129
  * module (`plugins/ad4m/wakerSubscriptionManager.ts`) rather than carrying its
22979
23130
  * own copy. Any behaviour change belongs here.
22980
23131
  */
23132
+ /** The built-in `Container` (`Container.builtinUri`; not imported, so the
23133
+ * plugin bundle does not pull in the model layer). */
23134
+ const CONTAINER = "ad4m://Container";
22981
23135
  /** A letter, combining mark, digit or underscore: what a term must not touch. */
22982
23136
  const WORD_CHAR = "[\\p{L}\\p{M}\\p{N}_]";
22983
23137
  /**
@@ -23007,14 +23161,6 @@ const BREAKING_TAG = /^<\/?(?:p|div|br|hr|li|ul|ol|h[1-6]|blockquote|pre|tr|td|t
23007
23161
  */
23008
23162
  const ATTRIBUTES = new RegExp(ATTRIBUTE, "g");
23009
23163
  const MENTION_TARGET = /^\s+(?:href|data-id|data-did)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))$/i;
23010
- /**
23011
- * How much of a record's text the word check reads. Dropping markup costs time
23012
- * quadratic in a run of unclosed `<script>`, `<style>` or `<!--` openers, so a
23013
- * very long text could hold the event loop for seconds, and a row that holds
23014
- * no term is checked again on every result while it is in the window. A term
23015
- * past this many characters does not wake.
23016
- */
23017
- const MENTION_TEXT_LIMIT = 16384;
23018
23164
  const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
23019
23165
  function decodeEntities(s) {
23020
23166
  return s.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi, (whole, ref) => {
@@ -23048,6 +23194,14 @@ function readableParts(text) {
23048
23194
  });
23049
23195
  return { visible: decodeEntities(visible), targets };
23050
23196
  }
23197
+ /**
23198
+ * How much of a record's text the word check reads. Dropping markup costs time
23199
+ * quadratic in a run of unclosed `<script>`, `<style>` or `<!--` openers, so a
23200
+ * very long text could hold the event loop for seconds, and a row that holds
23201
+ * no term is checked again on every result while it is in the window. A term
23202
+ * past this many characters does not wake.
23203
+ */
23204
+ const MENTION_TEXT_LIMIT = 16384;
23051
23205
  /**
23052
23206
  * Whether `text` holds one of `terms` as a whole word, case-insensitively:
23053
23207
  * "Data" is in "hi Data!", "@data" and "Data's turn", not in "metadata" or
@@ -23062,7 +23216,9 @@ function readableParts(text) {
23062
23216
  * is how a mention by DID is found when the DID is not in the visible text.
23063
23217
  *
23064
23218
  * The mention query's `contains` matches substrings (model query has no word
23065
- * match); this is the check that keeps "data" from waking on "metadata".
23219
+ * match); this is the check that keeps "data" from waking on "metadata" when
23220
+ * a record is found through its text alone ({@link mentionOf}).
23221
+ *
23066
23222
  * It reads the first {@link MENTION_TEXT_LIMIT} characters only.
23067
23223
  */
23068
23224
  function holdsAWholeWordTerm(text, terms) {
@@ -23076,9 +23232,95 @@ function holdsAWholeWordTerm(text, terms) {
23076
23232
  return new RegExp(`(?<!${WORD_CHAR})${escaped}(?!${WORD_CHAR})`, "iu").test(visible);
23077
23233
  });
23078
23234
  }
23079
- /** The built-in `Container` (`Container.builtinUri`; not imported, so the
23080
- * plugin bundle does not pull in the model layer). */
23081
- const CONTAINER = "ad4m://Container";
23235
+ /** The provenance {@link MentionMessage} carries, from one link. */
23236
+ function provenanceOf(link, via) {
23237
+ const provenance = {
23238
+ verified: link?.proof?.valid === true,
23239
+ via,
23240
+ };
23241
+ if (typeof link?.author === "string")
23242
+ provenance.author = link.author;
23243
+ if (typeof link?.timestamp === "string")
23244
+ provenance.timestamp = link.timestamp;
23245
+ return provenance;
23246
+ }
23247
+ /** The links a model row carries for `key` under `__links`, oldest first. */
23248
+ function rowLinks(row, key) {
23249
+ const links = row?.__links?.[key];
23250
+ return Array.isArray(links) ? links : [];
23251
+ }
23252
+ /** `uri` URI-decoded, or as it is when it is not valid percent-encoding. */
23253
+ function decoded(uri) {
23254
+ try {
23255
+ return decodeURIComponent(uri);
23256
+ }
23257
+ catch {
23258
+ return uri;
23259
+ }
23260
+ }
23261
+ /**
23262
+ * The text a link's target holds, read as the executor reads a string property
23263
+ * (`parse_literal_value`): `literal:string:` decoded, `literal:json:` parsed (a signed
23264
+ * expression to its `data`), any other URI as it is. `undefined` when that is not a string.
23265
+ */
23266
+ function textOf(target) {
23267
+ if (typeof target !== "string")
23268
+ return undefined;
23269
+ if (!target.startsWith("literal:"))
23270
+ return target;
23271
+ const body = target.slice("literal:".length);
23272
+ if (body.startsWith("string:"))
23273
+ return decoded(body.slice("string:".length));
23274
+ if (body.startsWith("json:")) {
23275
+ const json = decoded(body.slice("json:".length));
23276
+ let value;
23277
+ try {
23278
+ value = JSON.parse(json);
23279
+ }
23280
+ catch {
23281
+ return json;
23282
+ }
23283
+ if (value && typeof value === "object" && "data" in value && "author" in value && "proof" in value) {
23284
+ value = value.data;
23285
+ }
23286
+ return typeof value === "string" ? value : undefined;
23287
+ }
23288
+ if (/^(?:number|boolean):/.test(body))
23289
+ return undefined;
23290
+ return target;
23291
+ }
23292
+ /**
23293
+ * Whether a row of one of the mention subscription's two model queries mentions the
23294
+ * subscription's agent, and the provenance of the link it does so in; `null` when it does not.
23295
+ *
23296
+ * - A row of the query over Mentioning: a verified link to the agent's DID that another agent
23297
+ * wrote, in the row's `__links.mentions`. It wakes whatever the record's text says, or
23298
+ * whether it has any: WE's chip label may run into the next word ("@Datai have…"), and a WE
23299
+ * post's mention sits on its root, which has no text. Its provenance is that link's (the
23300
+ * newest such).
23301
+ * - A row of the query over TextContent: the query matched a substring, so the text must hold
23302
+ * a term as a whole word ({@link holdsAWholeWordTerm}), and so must the text of a verified
23303
+ * link another agent wrote, in `__links.text`. Its provenance is that link's (the newest
23304
+ * such). The row's `text` is the newest text link's, whoever wrote it, so it does not say
23305
+ * whose words they are.
23306
+ *
23307
+ * `via` says which it was. A record both queries find wakes once, through the query that
23308
+ * reports it first ({@link WakerSubscriptionManager}).
23309
+ */
23310
+ function mentionOf(row, sub) {
23311
+ const did = sub.did;
23312
+ const byOthers = (links) => links.filter((l) => typeof l.author === "string" && l.author !== did);
23313
+ const linked = byOthers(rowLinks(row, "mentions")).filter((l) => l.data?.target === did && l.proof?.valid === true);
23314
+ if (did && linked.length)
23315
+ return provenanceOf(linked[linked.length - 1], "mentions");
23316
+ const terms = sub.terms ?? [];
23317
+ const names = (text) => typeof text === "string" && holdsAWholeWordTerm(text, terms);
23318
+ const text = Array.isArray(row?.text) ? row.text.join(" ") : row?.text;
23319
+ if (!names(text))
23320
+ return null;
23321
+ const naming = byOthers(rowLinks(row, "text")).filter((l) => l.proof?.valid === true && names(textOf(l.data?.target)));
23322
+ return naming.length ? provenanceOf(naming[naming.length - 1], "text") : null;
23323
+ }
23082
23324
  /**
23083
23325
  * Add a short cause hint to known subscription failures.
23084
23326
  * The executor needs its main key to register a live query; on a restarted
@@ -23088,13 +23330,13 @@ function hintFor(msg) {
23088
23330
  // "Executor is locked" is the current executor's message; "main key not
23089
23331
  // found" is what older executors (and unrelated key lookups) say for the
23090
23332
  // same locked state. Either way the caller cannot fix it themselves: keys
23091
- // live in memory only, so every restart locks the node again and only its
23333
+ // live in memory only, so every restart locks the executor again and only its
23092
23334
  // operator can unlock it.
23093
23335
  if (/executor is locked/i.test(msg) || /main key not found/i.test(msg)) {
23094
- 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";
23336
+ 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";
23095
23337
  }
23096
23338
  if (/timed out after \d+ms/i.test(msg)) {
23097
- 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";
23339
+ 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";
23098
23340
  }
23099
23341
  return "";
23100
23342
  }
@@ -23124,6 +23366,7 @@ async function withTimeout(promise, ms, message) {
23124
23366
  }
23125
23367
  class WakerSubscriptionManager {
23126
23368
  constructor(options) {
23369
+ /** Per subscription its proxies: one, or a mention subscription's text and mention queries. */
23127
23370
  this.proxies = new Map();
23128
23371
  this.activeSubscriptions = new Map();
23129
23372
  /** Subscriptions the executor rejected, waiting to be re-attempted. */
@@ -23193,21 +23436,40 @@ class WakerSubscriptionManager {
23193
23436
  throw new Error("WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options");
23194
23437
  }
23195
23438
  const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;
23196
- if (sub.type === "mention" && sub.className && !sub.terms?.length) {
23197
- // Without terms the whole-word check cannot run, and every substring
23198
- // ("metadata" for "data") would wake the agent.
23199
- throw new Error(`Waker subscription ${sub.id}: a mention subscription needs its terms (get_mention_waker_config returns them)`);
23439
+ if (sub.type === "mention" &&
23440
+ (!sub.className || !sub.terms?.length || !sub.did || !sub.mentionQuery || !sub.mentionClass)) {
23441
+ // Without terms the whole-word check cannot run, so every substring
23442
+ // ("metadata" for "data") would wake the agent; without the DID no link
23443
+ // can be told to be someone else's; without the mention query a mention
23444
+ // link on a record with no text (a WE post's root) never wakes it.
23445
+ throw new Error(`Waker subscription ${sub.id}: a mention subscription needs its TextContent class, terms, DID and Mentioning query (get_mention_waker_config returns them)`);
23200
23446
  }
23201
23447
  this.logger.info(`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`);
23202
23448
  this.logger.info(`[waker] ${sub.id}: ${sub.className ? `model query over ${sub.className}` : "SPARQL query"}:\n${sub.query}`);
23449
+ if (sub.mentionQuery) {
23450
+ this.logger.info(`[waker] ${sub.id}: model query over ${sub.mentionClass}:\n${sub.mentionQuery}`);
23451
+ }
23203
23452
  const proxy = sub.className
23204
23453
  ? new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient, sub.className)
23205
23454
  : new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
23455
+ const mentionProxy = sub.mentionQuery
23456
+ ? new QuerySubscriptionProxy(sub.perspective, sub.mentionQuery, this.perspectiveClient, sub.mentionClass)
23457
+ : undefined;
23458
+ const proxies = mentionProxy ? [proxy, mentionProxy] : [proxy];
23459
+ const disposeProxies = () => {
23460
+ for (const p of proxies) {
23461
+ try {
23462
+ p.dispose();
23463
+ }
23464
+ catch { }
23465
+ }
23466
+ };
23206
23467
  // Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
23207
23468
  // rejects this promise internally when subscribe() fails, and if nobody catches
23208
23469
  // it before the next microtask it crashes the process.
23209
- if (proxy.initialized && typeof proxy.initialized.catch === "function") {
23210
- proxy.initialized.catch(() => { });
23470
+ for (const p of proxies) {
23471
+ if (p.initialized && typeof p.initialized.catch === "function")
23472
+ p.initialized.catch(() => { });
23211
23473
  }
23212
23474
  // One deadline for the whole handshake: `proxy.subscribe()` and the
23213
23475
  // `initialized` promise it resolves share the budget, so a hang in either
@@ -23218,23 +23480,17 @@ class WakerSubscriptionManager {
23218
23480
  ? withTimeout(step, Math.max(0, budgetMs - (Date.now() - startedAt)), `${what} timed out after ${budgetMs}ms`)
23219
23481
  : step;
23220
23482
  try {
23221
- await bounded(proxy.subscribe(), "subscribe handshake");
23483
+ await bounded(Promise.all(proxies.map((p) => p.subscribe())), "subscribe handshake");
23222
23484
  if (this.isStale(sub.id, token)) {
23223
- try {
23224
- proxy.dispose();
23225
- }
23226
- catch { }
23485
+ disposeProxies();
23227
23486
  return;
23228
23487
  }
23229
- await bounded(proxy.initialized, "subscription initialization");
23488
+ await bounded(Promise.all(proxies.map((p) => p.initialized)), "subscription initialization");
23230
23489
  }
23231
23490
  catch (err) {
23232
23491
  const msg = err?.message ?? String(err);
23233
23492
  this.logger.warn(`[waker] ${sub.id}: subscription failed — ${msg}`);
23234
- try {
23235
- proxy.dispose();
23236
- }
23237
- catch { }
23493
+ disposeProxies();
23238
23494
  // A dispose that landed mid-attempt wins: don't re-queue something the
23239
23495
  // caller has since asked us to forget.
23240
23496
  if (this.isStale(sub.id, token))
@@ -23259,10 +23515,7 @@ class WakerSubscriptionManager {
23259
23515
  : ""));
23260
23516
  }
23261
23517
  if (this.isStale(sub.id, token)) {
23262
- try {
23263
- proxy.dispose();
23264
- }
23265
- catch { }
23518
+ disposeProxies();
23266
23519
  return;
23267
23520
  }
23268
23521
  this.pendingSubscriptions.delete(sub.id);
@@ -23277,8 +23530,9 @@ class WakerSubscriptionManager {
23277
23530
  }
23278
23531
  // `opening` is the result the subscription holds when it opens (`proxy.result`): `onResult`
23279
23532
  // only reports later changes, so this is the one chance to see what was written meanwhile.
23280
- const handleResult = async (result, opening = false) => {
23281
- 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)}`);
23533
+ // `of`: the query the result is from, for the log (a mention subscription has two).
23534
+ const handleResult = async (result, opening = false, of = "") => {
23535
+ this.logger.info(`[waker] ${sub.id}: ${opening ? "opening result" : "onResult fired"}${of} — type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);
23282
23536
  // A model subscription delivers `{ instances }`, SPARQL an array of
23283
23537
  // rows. Anything else (e.g. `false` on a disconnect/reconnect) is
23284
23538
  // ignored.
@@ -23288,26 +23542,25 @@ class WakerSubscriptionManager {
23288
23542
  return;
23289
23543
  }
23290
23544
  if (sub.type === "mention") {
23291
- // For mention subscriptions: track seen record ids.
23292
- // Only wake for records we haven't seen before.
23545
+ // For mention subscriptions: track seen record ids, across both queries, and wake only
23546
+ // for records not seen before, so a record both find wakes once, through the query that
23547
+ // reports it first.
23293
23548
  const currentSeen = this.seenMessages.get(sub.id) ?? new Set();
23294
23549
  const newMessages = [];
23295
- const terms = sub.terms ?? [];
23550
+ const provenance = new Map();
23296
23551
  for (const item of rows) {
23297
- // A SPARQL row names the record as `source`, a model row as `id`.
23298
- const address = sub.className ? item?.id : item?.source;
23552
+ const address = item?.id;
23299
23553
  if (typeof address !== "string" || !address || currentSeen.has(address))
23300
23554
  continue;
23301
- if (terms.length) {
23302
- // The mention query matched a substring; wake only on a whole word.
23303
- const text = Array.isArray(item.text) ? item.text.join(" ") : item.text;
23304
- if (typeof text !== "string" || !holdsAWholeWordTerm(text, terms)) {
23305
- this.logger.debug(`[waker] ${sub.id}: ${address} holds no term as a whole word, skipping`);
23306
- continue;
23307
- }
23555
+ // A mention link as it is; the text, a whole word only.
23556
+ const mention = mentionOf(item, sub);
23557
+ if (!mention) {
23558
+ this.logger.debug(`[waker] ${sub.id}: ${address} has no verified mention link and no term as a whole word, skipping`);
23559
+ continue;
23308
23560
  }
23309
23561
  currentSeen.add(address);
23310
23562
  newMessages.push(address);
23563
+ provenance.set(address, mention);
23311
23564
  }
23312
23565
  if (newMessages.length === 0) {
23313
23566
  this.logger.info(`[waker] ${sub.id}: no new mention among ${rows.length} items, skipping`);
@@ -23332,7 +23585,7 @@ class WakerSubscriptionManager {
23332
23585
  const ancestors = await this.ancestorsOf(sub, msgAddr, parents);
23333
23586
  this.logger.info(`[waker] ${sub.id}: message ${msgAddr} has ${parents.length} parent(s): ${parents.join(", ")}` +
23334
23587
  (ancestors.length ? `; ancestors: ${ancestors.join(", ")}` : ""));
23335
- mentions.push({ address: msgAddr, parents, ancestors });
23588
+ mentions.push({ address: msgAddr, parents, ancestors, ...provenance.get(msgAddr) });
23336
23589
  }
23337
23590
  this.seenMessages.set(sub.id, currentSeen);
23338
23591
  const pending = this.undelivered.get(sub.id) ?? new Map();
@@ -23358,20 +23611,21 @@ class WakerSubscriptionManager {
23358
23611
  }
23359
23612
  };
23360
23613
  proxy.onResult((result) => handleResult(result));
23614
+ mentionProxy?.onResult((result) => handleResult(result, false, " (mention query)"));
23361
23615
  if (this.isStale(sub.id, token)) {
23362
- try {
23363
- proxy.dispose();
23364
- }
23365
- catch { }
23616
+ disposeProxies();
23366
23617
  return;
23367
23618
  }
23368
- this.proxies.set(sub.id, proxy);
23619
+ this.proxies.set(sub.id, proxies);
23369
23620
  this.activeSubscriptions.set(sub.id, sub);
23370
23621
  // After a restart this wakes on mentions written while the waker was down; on a new
23371
- // subscription it records the existing ones as history.
23372
- if (proxy.result !== undefined) {
23622
+ // subscription it records the existing ones as history. The mention query's first, so a
23623
+ // record both hold wakes through its mention link.
23624
+ for (const [p, of] of [[mentionProxy, " (mention query)"], [proxy, ""]]) {
23625
+ if (p?.result === undefined)
23626
+ continue;
23373
23627
  try {
23374
- await handleResult(proxy.result, true);
23628
+ await handleResult(p.result, true, of);
23375
23629
  }
23376
23630
  catch (e) {
23377
23631
  this.logger.warn(`[waker] ${sub.id}: reading the opening result failed: ${e?.message ?? e}`);
@@ -23434,16 +23688,15 @@ class WakerSubscriptionManager {
23434
23688
  dispose(id, persist = true) {
23435
23689
  // Invalidate any subscribe() for this id that is still awaiting.
23436
23690
  this.generations.set(id, (this.generations.get(id) ?? 0) + 1);
23437
- const proxy = this.proxies.get(id);
23438
- if (proxy) {
23691
+ for (const proxy of this.proxies.get(id) ?? []) {
23439
23692
  try {
23440
23693
  proxy.dispose();
23441
23694
  }
23442
23695
  catch {
23443
23696
  /* ignore */
23444
23697
  }
23445
- this.proxies.delete(id);
23446
23698
  }
23699
+ this.proxies.delete(id);
23447
23700
  const timer = this.debounceTimers.get(id);
23448
23701
  if (timer) {
23449
23702
  clearTimeout(timer);
@@ -24191,6 +24444,7 @@ exports.linkExpressionToWire = linkExpressionToWire;
24191
24444
  exports.linkMutationsToWire = linkMutationsToWire;
24192
24445
  exports.literal = literal;
24193
24446
  exports.looksLikeUri = looksLikeUri;
24447
+ exports.mentionOf = mentionOf;
24194
24448
  exports.neighbourhoodExpressionFromWire = neighbourhoodExpressionFromWire;
24195
24449
  exports.normalizeNamespaceString = normalizeNamespaceString;
24196
24450
  exports.normalizeSchemaType = normalizeSchemaType;