@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.js CHANGED
@@ -105,6 +105,7 @@ const LONG_METHODS = new Set([
105
105
  "language.publish",
106
106
  "neighbourhood.join",
107
107
  "neighbourhood.publish",
108
+ "perspective.runAgent",
108
109
  "perspective.runInterpretation",
109
110
  "perspective.runInterpretationWithHarness",
110
111
  "runtime.restartHolochain",
@@ -208,7 +209,7 @@ class ApiClient {
208
209
  ? new RpcError(401, event.reason || 'token expired or revoked')
209
210
  : closedError(event?.code === CLOSE_TRY_AGAIN_LATER ? event.reason : undefined));
210
211
  if (event?.code === CLOSE_AUTH_FAILED && this._ws === ws) {
211
- this._failAuth(event.reason || 'token expired or revoked');
212
+ this._failAuth(event.reason || 'Unauthorized access: the token expired or was revoked');
212
213
  }
213
214
  else {
214
215
  this._onClose(ws, event?.code === CLOSE_TRY_AGAIN_LATER ? event.reason : undefined);
@@ -1292,8 +1293,15 @@ class AgentClient {
1292
1293
  async entanglementProofPreFlight(deviceKey, deviceKeyType) {
1293
1294
  return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('agent.entanglementProofPreflight', { deviceKey, deviceKeyType });
1294
1295
  }
1295
- async requestCapability(authInfo) {
1296
- return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('agent.requestCapability', { authInfo });
1296
+ /**
1297
+ * Asks the executor for a capability token. `agent` names the agent the token will act
1298
+ * as: a managed user's email or an agent's DID; absent, the executor's main agent. That
1299
+ * agent's owner approves the request (the operator for the main agent, the user for
1300
+ * theirs). Returns the request id that {@link generateJwt} redeems with the approver's
1301
+ * six-digit code.
1302
+ */
1303
+ async requestCapability(authInfo, agent) {
1304
+ return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('agent.requestCapability', agent === undefined ? { authInfo } : { authInfo, agent });
1297
1305
  }
1298
1306
  async permitCapability(auth) {
1299
1307
  return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('agent.permitCapability', { auth });
@@ -1329,6 +1337,18 @@ class AgentClient {
1329
1337
  async verifyEmailCode(email, code, verificationType) {
1330
1338
  return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('user.verifyEmail', { email, code, verificationType });
1331
1339
  }
1340
+ /** Revokes this client's user token. The executor then closes the client's sockets. */
1341
+ async logout() {
1342
+ return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('user.logout', {});
1343
+ }
1344
+ /**
1345
+ * Revokes every token of a user issued up to now, this client's own included, and closes
1346
+ * their sockets. A user leaves out `email` (or names themselves); the operator names the
1347
+ * user. Needs AGENT_UPDATE, which a login holds. Tokens from a later login work.
1348
+ */
1349
+ async revokeAllSessions(email) {
1350
+ return __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('user.revokeAllSessions', email === undefined ? {} : { email });
1351
+ }
1332
1352
  // Hosting methods
1333
1353
  async hostingUserInfo() {
1334
1354
  const info = (await __classPrivateFieldGet$c(this, _AgentClient_apiClient, "f").call('hosting.info', {})).userInfo ?? {
@@ -1822,6 +1842,8 @@ class SfuManager {
1822
1842
  this.rosterUnsubscribe = null;
1823
1843
  this.dataChannelUnsubscribe = null;
1824
1844
  this.disconnectedTimer = null;
1845
+ /** Running while the room's roster leaves this agent out: see `noticeRoster`. */
1846
+ this.unlistedTimer = null;
1825
1847
  this.neighbourhood = neighbourhood;
1826
1848
  this.neighbourhoodUrl = neighbourhoodUrl || "";
1827
1849
  this.roomId = roomId;
@@ -2108,6 +2130,37 @@ class SfuManager {
2108
2130
  this.renegotiationUnsubscribe = null;
2109
2131
  this.rosterUnsubscribe?.();
2110
2132
  this.rosterUnsubscribe = null;
2133
+ this.clearUnlistedTimer();
2134
+ }
2135
+ clearUnlistedTimer() {
2136
+ if (this.unlistedTimer) {
2137
+ clearTimeout(this.unlistedTimer);
2138
+ this.unlistedTimer = null;
2139
+ }
2140
+ }
2141
+ /**
2142
+ * The room's roster no longer lists this agent while `pc` is the call's:
2143
+ * the server has dropped this session, and ICE may not say so. In E6
2144
+ * (CI job 53158) one of six sessions never started a rebuild after a
2145
+ * 20 s outage the server had dropped it for. Rebuild once the roster has
2146
+ * left this agent out for `UNLISTED_GRACE_MS`; a roster that lists it
2147
+ * again in that time cancels, since one published just before this
2148
+ * join landed can arrive after it.
2149
+ */
2150
+ noticeRoster(pc, dids) {
2151
+ if (dids.includes(this.agentDid)) {
2152
+ this.clearUnlistedTimer();
2153
+ return;
2154
+ }
2155
+ if (this.unlistedTimer)
2156
+ return;
2157
+ this.unlistedTimer = setTimeout(() => {
2158
+ this.unlistedTimer = null;
2159
+ if (this.state.peerConnection !== pc)
2160
+ return;
2161
+ console.info("SFU: the room no longer lists this session, rebuilding the call");
2162
+ void this.reconnect();
2163
+ }, SfuManager.UNLISTED_GRACE_MS);
2111
2164
  }
2112
2165
  /** Undo a join that failed part way: its subscription and its connection. */
2113
2166
  abandon(pc) {
@@ -2142,8 +2195,10 @@ class SfuManager {
2142
2195
  if (!ours(roster) || this.state.peerConnection !== pc)
2143
2196
  return;
2144
2197
  void joined.then(() => {
2145
- if (this.state.peerConnection === pc)
2146
- this.applyRoster(roster.participants, true);
2198
+ if (this.state.peerConnection !== pc)
2199
+ return;
2200
+ this.applyRoster(roster.participants, true);
2201
+ this.noticeRoster(pc, roster.participants);
2147
2202
  });
2148
2203
  });
2149
2204
  for (const unsubscribe of previous)
@@ -2357,6 +2412,8 @@ SfuManager.MAX_RECONNECTS = 3;
2357
2412
  SfuManager.REJOIN_WINDOW_MS = 120000;
2358
2413
  /** How long ICE may stay disconnected before a rebuild: the executor's `ICE_DISCONNECT_GRACE`. */
2359
2414
  SfuManager.DISCONNECT_GRACE_MS = 10000;
2415
+ /** How long the roster may leave this agent out before the call is rebuilt. */
2416
+ SfuManager.UNLISTED_GRACE_MS = 3000;
2360
2417
 
2361
2418
  /**
2362
2419
  * Peer-to-peer WebRTC mesh transport for the AD4M SDK Session interface.
@@ -7860,6 +7917,19 @@ class PerspectiveProxy {
7860
7917
  observationId, emitDebugEvents, options) {
7861
7918
  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);
7862
7919
  }
7920
+ /**
7921
+ * Ask a model something about this perspective, or ask it to change something, with the
7922
+ * executor's own tools — including the tools apps install for their records. It reads freely;
7923
+ * it writes only with the tools named in `settings.writeTools`, as you. Answers with the
7924
+ * model's final reply.
7925
+ *
7926
+ * @param messages the conversation so far, the person's request last
7927
+ * @param settings `context` (what the person is looking at), `writeTools`, `model`, `maxToolCalls`
7928
+ * @param options `signal` / `timeoutMs` (default {@link LONG_TIMEOUT_MS})
7929
+ */
7930
+ async runAgent(messages, settings, options) {
7931
+ return await __classPrivateFieldGet$6(this, _PerspectiveProxy_client, "f").runAgent(__classPrivateFieldGet$6(this, _PerspectiveProxy_handle, "f").uuid, messages, settings, options);
7932
+ }
7863
7933
  /**
7864
7934
  * Register a neighbourhood auto-processor on this perspective. The executor
7865
7935
  * then runs interpretation automatically over new source items (like Flux
@@ -8234,6 +8304,12 @@ class PerspectiveProxy {
8234
8304
  /**
8235
8305
  * Adds a pre-signed LinkExpression to the perspective.
8236
8306
  *
8307
+ * The executor checks the signature against `link.author` and stores the
8308
+ * verdict as `proof.valid`. If the same link (author, source, predicate,
8309
+ * target and timestamp) is already stored with a signature that verifies,
8310
+ * its stored proof is kept. The expression passed here is still returned
8311
+ * and, when Shared, committed to the neighbourhood as given.
8312
+ *
8237
8313
  * @param link - The signed LinkExpression to add
8238
8314
  * @param status - Whether the link should be shared
8239
8315
  * @param batchId - Optional batch ID to group this operation with others
@@ -9750,6 +9826,19 @@ class PerspectiveClient {
9750
9826
  emitDebugEvents,
9751
9827
  }, options);
9752
9828
  }
9829
+ /**
9830
+ * A conversation with a model in this perspective, using the executor's own tools: the tools
9831
+ * that read this perspective, and only the writing tools named in `writeTools`. Every tool a
9832
+ * session offers acts on this perspective alone, so tools about other perspectives, the agent
9833
+ * or the node (listing or publishing perspectives, the profile) are not available. Runs as the
9834
+ * caller, with the caller's capabilities, and answers with the model's final reply.
9835
+ *
9836
+ * Defaults to {@link LONG_TIMEOUT_MS}: an agent may read documentation and make many tool
9837
+ * calls before it answers.
9838
+ */
9839
+ async runAgent(uuid, messages, settings, options) {
9840
+ return __classPrivateFieldGet$5(this, _PerspectiveClient_apiClient, "f").call('perspective.runAgent', { uuid, messages, ...settings }, options);
9841
+ }
9753
9842
  /**
9754
9843
  * Register a neighbourhood auto-processor on this perspective. The executor's
9755
9844
  * watch loop then runs interpretation automatically over new source items
@@ -9968,6 +10057,8 @@ class RuntimeClient {
9968
10057
  async removeKnownLinkLanguageTemplates(addresses) {
9969
10058
  return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, "f").call('runtime.removeLinkLanguageTemplates', { addresses });
9970
10059
  }
10060
+ /** Every link-language template the executor knows, with its meta (name, description,
10061
+ * `possibleTemplateParams`). A template whose meta cannot be read is left out. */
9971
10062
  async knownLinkLanguageTemplates() {
9972
10063
  return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, "f").call('runtime.linkLanguageTemplates', {});
9973
10064
  }
@@ -21814,13 +21905,13 @@ class LanguageLanguageInput {
21814
21905
  * const runs = await InterpretationRun.findAll(perspective);
21815
21906
  * const configs = await AutoProcessorConfig.findAll(perspective);
21816
21907
  */
21817
- var __decorate$3 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
21908
+ var __decorate$4 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
21818
21909
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
21819
21910
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21820
21911
  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;
21821
21912
  return c > 3 && r && Object.defineProperty(target, key, r), r;
21822
21913
  };
21823
- var __metadata$3 = (undefined && undefined.__metadata) || function (k, v) {
21914
+ var __metadata$4 = (undefined && undefined.__metadata) || function (k, v) {
21824
21915
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
21825
21916
  };
21826
21917
  // ── AutoProcessorConfig ─────────────────────────────────────────────────────
@@ -21861,71 +21952,71 @@ let AutoProcessorConfig = class AutoProcessorConfig extends Ad4mModel {
21861
21952
  // `batchMax` + `claimTtlMs` — the Rust SDNA takes the same shape.
21862
21953
  }
21863
21954
  };
21864
- __decorate$3([
21955
+ __decorate$4([
21865
21956
  Property({ through: "ad4m://processor_id", required: true, identity: true }),
21866
- __metadata$3("design:type", String)
21957
+ __metadata$4("design:type", String)
21867
21958
  ], AutoProcessorConfig.prototype, "processorId", void 0);
21868
- __decorate$3([
21959
+ __decorate$4([
21869
21960
  Property({ through: "ad4m://source_scope_query", required: true }),
21870
- __metadata$3("design:type", String)
21961
+ __metadata$4("design:type", String)
21871
21962
  ], AutoProcessorConfig.prototype, "sourceScopeQuery", void 0);
21872
- __decorate$3([
21963
+ __decorate$4([
21873
21964
  Optional({ through: "ad4m://base_prefix" }),
21874
- __metadata$3("design:type", String)
21965
+ __metadata$4("design:type", String)
21875
21966
  ], AutoProcessorConfig.prototype, "basePrefix", void 0);
21876
- __decorate$3([
21967
+ __decorate$4([
21877
21968
  HasMany({ through: "ad4m://interpretation_class", datatype: "xsd:string" }),
21878
- __metadata$3("design:type", Array)
21969
+ __metadata$4("design:type", Array)
21879
21970
  ], AutoProcessorConfig.prototype, "interpretationClasses", void 0);
21880
- __decorate$3([
21971
+ __decorate$4([
21881
21972
  HasMany({ through: "ad4m://flow", datatype: "xsd:string" }),
21882
- __metadata$3("design:type", Array)
21973
+ __metadata$4("design:type", Array)
21883
21974
  ], AutoProcessorConfig.prototype, "flows", void 0);
21884
- __decorate$3([
21975
+ __decorate$4([
21885
21976
  Property({ through: "ad4m://debounce_ms", required: true }),
21886
- __metadata$3("design:type", String)
21977
+ __metadata$4("design:type", String)
21887
21978
  ], AutoProcessorConfig.prototype, "debounceMs", void 0);
21888
- __decorate$3([
21979
+ __decorate$4([
21889
21980
  Optional({ through: "ad4m://batch_min" }),
21890
- __metadata$3("design:type", String)
21981
+ __metadata$4("design:type", String)
21891
21982
  ], AutoProcessorConfig.prototype, "batchMin", void 0);
21892
- __decorate$3([
21983
+ __decorate$4([
21893
21984
  Property({ through: "ad4m://batch_max", required: true }),
21894
- __metadata$3("design:type", String)
21985
+ __metadata$4("design:type", String)
21895
21986
  ], AutoProcessorConfig.prototype, "batchMax", void 0);
21896
- __decorate$3([
21987
+ __decorate$4([
21897
21988
  Optional({ through: "ad4m://max_wait_ms" }),
21898
- __metadata$3("design:type", String)
21989
+ __metadata$4("design:type", String)
21899
21990
  ], AutoProcessorConfig.prototype, "maxWaitMs", void 0);
21900
- __decorate$3([
21991
+ __decorate$4([
21901
21992
  Property({ through: "ad4m://claim_ttl_ms", required: true }),
21902
- __metadata$3("design:type", String)
21993
+ __metadata$4("design:type", String)
21903
21994
  ], AutoProcessorConfig.prototype, "claimTtlMs", void 0);
21904
- __decorate$3([
21995
+ __decorate$4([
21905
21996
  Optional({ through: "ad4m://source_window_ms" }),
21906
- __metadata$3("design:type", String)
21997
+ __metadata$4("design:type", String)
21907
21998
  ], AutoProcessorConfig.prototype, "sourceWindowMs", void 0);
21908
- __decorate$3([
21999
+ __decorate$4([
21909
22000
  Optional({ through: "ad4m://dedup_strategy" }),
21910
- __metadata$3("design:type", String)
22001
+ __metadata$4("design:type", String)
21911
22002
  ], AutoProcessorConfig.prototype, "dedupStrategy", void 0);
21912
- __decorate$3([
22003
+ __decorate$4([
21913
22004
  Optional({ through: "ad4m://existing_scope" }),
21914
- __metadata$3("design:type", String)
22005
+ __metadata$4("design:type", String)
21915
22006
  ], AutoProcessorConfig.prototype, "existingScope", void 0);
21916
- __decorate$3([
22007
+ __decorate$4([
21917
22008
  Optional({ through: "ad4m://mint_scope" }),
21918
- __metadata$3("design:type", String)
22009
+ __metadata$4("design:type", String)
21919
22010
  ], AutoProcessorConfig.prototype, "mintScope", void 0);
21920
- __decorate$3([
22011
+ __decorate$4([
21921
22012
  Optional({ through: "ad4m://max_tool_calls" }),
21922
- __metadata$3("design:type", String)
22013
+ __metadata$4("design:type", String)
21923
22014
  ], AutoProcessorConfig.prototype, "maxToolCalls", void 0);
21924
- __decorate$3([
22015
+ __decorate$4([
21925
22016
  Optional({ through: "ad4m://emit_debug_events", resolveLanguage: "literal" }),
21926
- __metadata$3("design:type", String)
22017
+ __metadata$4("design:type", String)
21927
22018
  ], AutoProcessorConfig.prototype, "emitDebugEvents", void 0);
21928
- AutoProcessorConfig = __decorate$3([
22019
+ AutoProcessorConfig = __decorate$4([
21929
22020
  Model$1({ name: "AutoProcessor" })
21930
22021
  ], AutoProcessorConfig);
21931
22022
  // ── InterpretationRun ───────────────────────────────────────────────────────
@@ -21949,39 +22040,39 @@ let InterpretationRun = class InterpretationRun extends Ad4mModel {
21949
22040
  this.sources = [];
21950
22041
  }
21951
22042
  };
21952
- __decorate$3([
22043
+ __decorate$4([
21953
22044
  Property({ through: "ad4m://interp/run_id", required: true, identity: true }),
21954
- __metadata$3("design:type", String)
22045
+ __metadata$4("design:type", String)
21955
22046
  ], InterpretationRun.prototype, "runId", void 0);
21956
- __decorate$3([
22047
+ __decorate$4([
21957
22048
  Optional({ through: "ad4m://interp/model" }),
21958
- __metadata$3("design:type", String)
22049
+ __metadata$4("design:type", String)
21959
22050
  ], InterpretationRun.prototype, "model", void 0);
21960
- __decorate$3([
22051
+ __decorate$4([
21961
22052
  Optional({ through: "ad4m://interp/prompt_version" }),
21962
- __metadata$3("design:type", String)
22053
+ __metadata$4("design:type", String)
21963
22054
  ], InterpretationRun.prototype, "promptVersion", void 0);
21964
- __decorate$3([
22055
+ __decorate$4([
21965
22056
  Optional({ through: "ad4m://interp/ran_at" }),
21966
- __metadata$3("design:type", String)
22057
+ __metadata$4("design:type", String)
21967
22058
  ], InterpretationRun.prototype, "ranAt", void 0);
21968
- __decorate$3([
22059
+ __decorate$4([
21969
22060
  Optional({ through: "ad4m://interp/processor" }),
21970
- __metadata$3("design:type", String)
22061
+ __metadata$4("design:type", String)
21971
22062
  ], InterpretationRun.prototype, "processor", void 0);
21972
- __decorate$3([
22063
+ __decorate$4([
21973
22064
  HasMany({ through: "ad4m://interp/sources", datatype: "xsd:string" }),
21974
- __metadata$3("design:type", Array)
22065
+ __metadata$4("design:type", Array)
21975
22066
  ], InterpretationRun.prototype, "sources", void 0);
21976
- __decorate$3([
22067
+ __decorate$4([
21977
22068
  Optional({ through: "ad4m://interp/debug_prompt", resolveLanguage: "literal" }),
21978
- __metadata$3("design:type", String)
22069
+ __metadata$4("design:type", String)
21979
22070
  ], InterpretationRun.prototype, "debugPrompt", void 0);
21980
- __decorate$3([
22071
+ __decorate$4([
21981
22072
  Optional({ through: "ad4m://interp/debug_response", resolveLanguage: "literal" }),
21982
- __metadata$3("design:type", String)
22073
+ __metadata$4("design:type", String)
21983
22074
  ], InterpretationRun.prototype, "debugResponse", void 0);
21984
- InterpretationRun = __decorate$3([
22075
+ InterpretationRun = __decorate$4([
21985
22076
  Model$1({ name: "InterpretationRun" })
21986
22077
  ], InterpretationRun);
21987
22078
  // ── InterpretationOverlay ───────────────────────────────────────────────────
@@ -22011,15 +22102,15 @@ let InterpretationOverlay = class InterpretationOverlay extends Ad4mModel {
22011
22102
  this.kind = "";
22012
22103
  }
22013
22104
  };
22014
- __decorate$3([
22105
+ __decorate$4([
22015
22106
  Property({ through: "ad4m://interp/kind", required: true }),
22016
- __metadata$3("design:type", String)
22107
+ __metadata$4("design:type", String)
22017
22108
  ], InterpretationOverlay.prototype, "kind", void 0);
22018
- __decorate$3([
22109
+ __decorate$4([
22019
22110
  Optional({ through: "ad4m://interp/run" }),
22020
- __metadata$3("design:type", String)
22111
+ __metadata$4("design:type", String)
22021
22112
  ], InterpretationOverlay.prototype, "run", void 0);
22022
- InterpretationOverlay = __decorate$3([
22113
+ InterpretationOverlay = __decorate$4([
22023
22114
  Model$1({ name: "InterpretationOverlay" })
22024
22115
  ], InterpretationOverlay);
22025
22116
 
@@ -22043,13 +22134,13 @@ InterpretationOverlay = __decorate$3([
22043
22134
  * - the SDNA-parity test locks TS/Rust drift against
22044
22135
  * `rust-executor/src/perspectives/hardwired_sdna/flow_transition_proposal.json`.
22045
22136
  */
22046
- var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22137
+ var __decorate$3 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22047
22138
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22048
22139
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22049
22140
  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;
22050
22141
  return c > 3 && r && Object.defineProperty(target, key, r), r;
22051
22142
  };
22052
- var __metadata$2 = (undefined && undefined.__metadata) || function (k, v) {
22143
+ var __metadata$3 = (undefined && undefined.__metadata) || function (k, v) {
22053
22144
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22054
22145
  };
22055
22146
  /**
@@ -22156,55 +22247,55 @@ let FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel {
22156
22247
  // of the proposal's own links (all written together during create_subject).
22157
22248
  }
22158
22249
  };
22159
- __decorate$2([
22250
+ __decorate$3([
22160
22251
  Property({ through: "ad4m://flow/instance", required: true, identity: true }),
22161
- __metadata$2("design:type", String)
22252
+ __metadata$3("design:type", String)
22162
22253
  ], FlowTransitionProposal.prototype, "flowInstance", void 0);
22163
- __decorate$2([
22254
+ __decorate$3([
22164
22255
  Property({ through: "ad4m://flow/from_state", required: true }),
22165
- __metadata$2("design:type", String)
22256
+ __metadata$3("design:type", String)
22166
22257
  ], FlowTransitionProposal.prototype, "fromState", void 0);
22167
- __decorate$2([
22258
+ __decorate$3([
22168
22259
  Property({ through: "ad4m://flow/to_state", required: true }),
22169
- __metadata$2("design:type", String)
22260
+ __metadata$3("design:type", String)
22170
22261
  ], FlowTransitionProposal.prototype, "toState", void 0);
22171
- __decorate$2([
22262
+ __decorate$3([
22172
22263
  Property({ through: "ad4m://flow/proposer", required: true, getter: PROPOSER_GETTER, datatype: "xsd:string" }),
22173
- __metadata$2("design:type", String)
22264
+ __metadata$3("design:type", String)
22174
22265
  ], FlowTransitionProposal.prototype, "proposer", void 0);
22175
- __decorate$2([
22266
+ __decorate$3([
22176
22267
  HasMany({ through: "ad4m://flow/evidence", datatype: "xsd:string" }),
22177
- __metadata$2("design:type", Array)
22268
+ __metadata$3("design:type", Array)
22178
22269
  ], FlowTransitionProposal.prototype, "evidence", void 0);
22179
- __decorate$2([
22270
+ __decorate$3([
22180
22271
  Property({ through: "ad4m://flow/evidence_hashes", required: true }),
22181
- __metadata$2("design:type", String)
22272
+ __metadata$3("design:type", String)
22182
22273
  ], FlowTransitionProposal.prototype, "evidenceHashes", void 0);
22183
- __decorate$2([
22274
+ __decorate$3([
22184
22275
  HasMany({ through: "ad4m://flow/output", datatype: "xsd:string" }),
22185
- __metadata$2("design:type", Array)
22276
+ __metadata$3("design:type", Array)
22186
22277
  ], FlowTransitionProposal.prototype, "outputs", void 0);
22187
- __decorate$2([
22278
+ __decorate$3([
22188
22279
  Property({ through: "ad4m://flow/outputs_hash" }),
22189
- __metadata$2("design:type", String)
22280
+ __metadata$3("design:type", String)
22190
22281
  ], FlowTransitionProposal.prototype, "outputsHash", void 0);
22191
- __decorate$2([
22282
+ __decorate$3([
22192
22283
  Property({ through: "ad4m://flow/nonce" }),
22193
- __metadata$2("design:type", String)
22284
+ __metadata$3("design:type", String)
22194
22285
  ], FlowTransitionProposal.prototype, "nonce", void 0);
22195
- __decorate$2([
22286
+ __decorate$3([
22196
22287
  Optional({ through: "ad4m://flow/run_uri" }),
22197
- __metadata$2("design:type", String)
22288
+ __metadata$3("design:type", String)
22198
22289
  ], FlowTransitionProposal.prototype, "runUri", void 0);
22199
- __decorate$2([
22290
+ __decorate$3([
22200
22291
  Optional({ through: "ad4m://flow/rationale" }),
22201
- __metadata$2("design:type", String)
22292
+ __metadata$3("design:type", String)
22202
22293
  ], FlowTransitionProposal.prototype, "rationale", void 0);
22203
- __decorate$2([
22294
+ __decorate$3([
22204
22295
  HasMany({ through: "ad4m://acceptedBy", getter: ACCEPTED_BY_GETTER, readOnly: true }),
22205
- __metadata$2("design:type", Array)
22296
+ __metadata$3("design:type", Array)
22206
22297
  ], FlowTransitionProposal.prototype, "acceptedBy", void 0);
22207
- FlowTransitionProposal = __decorate$2([
22298
+ FlowTransitionProposal = __decorate$3([
22208
22299
  Model$1({ name: "FlowTransitionProposal" })
22209
22300
  ], FlowTransitionProposal);
22210
22301
  // ── FlowInstanceRecord ──────────────────────────────────────────────────────
@@ -22264,25 +22355,25 @@ let FlowInstanceRecord = class FlowInstanceRecord extends Ad4mModel {
22264
22355
  // of the instance's own links (all written together during `mint_flow_instance`).
22265
22356
  }
22266
22357
  };
22267
- __decorate$2([
22358
+ __decorate$3([
22268
22359
  Property({ through: "ad4m://flow/flow_uri", required: true, identity: true }),
22269
- __metadata$2("design:type", String)
22360
+ __metadata$3("design:type", String)
22270
22361
  ], FlowInstanceRecord.prototype, "flowUri", void 0);
22271
- __decorate$2([
22362
+ __decorate$3([
22272
22363
  Property({ through: "ad4m://flow/base", required: true }),
22273
- __metadata$2("design:type", String)
22364
+ __metadata$3("design:type", String)
22274
22365
  ], FlowInstanceRecord.prototype, "subject", void 0);
22275
- FlowInstanceRecord = __decorate$2([
22366
+ FlowInstanceRecord = __decorate$3([
22276
22367
  Model$1({ name: "FlowInstance" })
22277
22368
  ], FlowInstanceRecord);
22278
22369
 
22279
- var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22370
+ var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22280
22371
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22281
22372
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22282
22373
  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;
22283
22374
  return c > 3 && r && Object.defineProperty(target, key, r), r;
22284
22375
  };
22285
- var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22376
+ var __metadata$2 = (undefined && undefined.__metadata) || function (k, v) {
22286
22377
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22287
22378
  };
22288
22379
  /**
@@ -22308,6 +22399,10 @@ var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22308
22399
  * reads it by its URI, `ad4m://TextContent`, so a perspective never stores it
22309
22400
  * and an app class named `TextContent` does not replace it. `register()` on
22310
22401
  * it writes nothing.
22402
+ *
22403
+ * The waker's mention subscription (`get_mention_waker_config`) reads it for
22404
+ * the agent's names in the text. Mention links it reads through
22405
+ * {@link Mentioning}, with text or without.
22311
22406
  */
22312
22407
  let TextContent = class TextContent extends Ad4mModel {
22313
22408
  constructor() {
@@ -22318,14 +22413,70 @@ let TextContent = class TextContent extends Ad4mModel {
22318
22413
  };
22319
22414
  /** The URI the executor reads it by. */
22320
22415
  TextContent.builtinUri = "ad4m://TextContent";
22321
- __decorate$1([
22416
+ __decorate$2([
22322
22417
  Property({ through: "ad4m://text" }),
22323
- __metadata$1("design:type", String)
22418
+ __metadata$2("design:type", String)
22324
22419
  ], TextContent.prototype, "text", void 0);
22325
- TextContent = __decorate$1([
22420
+ TextContent = __decorate$2([
22326
22421
  Model$1({ name: "TextContent", abstract: true })
22327
22422
  ], TextContent);
22328
22423
 
22424
+ var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22425
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22426
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22427
+ 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;
22428
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
22429
+ };
22430
+ var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22431
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22432
+ };
22433
+ /**
22434
+ * The built-in abstract class `Mentioning { mentions }`: a record that
22435
+ * mentions agents — a post, a message, a block of a document. `mentions` is
22436
+ * a relation to their DIDs.
22437
+ *
22438
+ * Querying it reads every class that has a relation named `mentions`, or one
22439
+ * aliased to `mentions`, under any predicate, whether or not the class has
22440
+ * text. A class whose relation has another name aliases it:
22441
+ *
22442
+ * ```typescript
22443
+ * @Model({ name: "Note", implements: [Mentioning] })
22444
+ * class Note extends Ad4mModel {
22445
+ * @HasMany({ through: "app://cc", alias: { Mentioning: "mentions" } })
22446
+ * cc: string[] = [];
22447
+ * }
22448
+ *
22449
+ * const mentioningMe = await Mentioning.findAll(perspective, { where: { mentions: myDid } });
22450
+ * ```
22451
+ *
22452
+ * The waker's mention subscription (`get_mention_waker_config`) reads it: a
22453
+ * record whose `mentions` links the agent's DID, in a link another agent
22454
+ * wrote, wakes the agent whatever its text says. Names in text it reads
22455
+ * through {@link TextContent}.
22456
+ *
22457
+ * Built in: the executor declares it (mirrors
22458
+ * `rust-executor/src/perspectives/hardwired_sdna/mentioning.json`) and reads
22459
+ * it by its URI, `ad4m://Mentioning`, so a perspective never stores it and an
22460
+ * app class named `Mentioning` does not replace it. `register()` on it writes
22461
+ * nothing.
22462
+ */
22463
+ let Mentioning = class Mentioning extends Ad4mModel {
22464
+ constructor() {
22465
+ super(...arguments);
22466
+ /** The agents (DIDs) the record mentions. */
22467
+ this.mentions = [];
22468
+ }
22469
+ };
22470
+ /** The URI the executor reads it by. */
22471
+ Mentioning.builtinUri = "ad4m://Mentioning";
22472
+ __decorate$1([
22473
+ HasMany({ through: "ad4m://mentions" }),
22474
+ __metadata$1("design:type", Array)
22475
+ ], Mentioning.prototype, "mentions", void 0);
22476
+ Mentioning = __decorate$1([
22477
+ Model$1({ name: "Mentioning", abstract: true })
22478
+ ], Mentioning);
22479
+
22329
22480
  var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22330
22481
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22331
22482
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -22974,6 +23125,9 @@ function parseLitBoolean(val) {
22974
23125
  * module (`plugins/ad4m/wakerSubscriptionManager.ts`) rather than carrying its
22975
23126
  * own copy. Any behaviour change belongs here.
22976
23127
  */
23128
+ /** The built-in `Container` (`Container.builtinUri`; not imported, so the
23129
+ * plugin bundle does not pull in the model layer). */
23130
+ const CONTAINER = "ad4m://Container";
22977
23131
  /** A letter, combining mark, digit or underscore: what a term must not touch. */
22978
23132
  const WORD_CHAR = "[\\p{L}\\p{M}\\p{N}_]";
22979
23133
  /**
@@ -23003,14 +23157,6 @@ const BREAKING_TAG = /^<\/?(?:p|div|br|hr|li|ul|ol|h[1-6]|blockquote|pre|tr|td|t
23003
23157
  */
23004
23158
  const ATTRIBUTES = new RegExp(ATTRIBUTE, "g");
23005
23159
  const MENTION_TARGET = /^\s+(?:href|data-id|data-did)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))$/i;
23006
- /**
23007
- * How much of a record's text the word check reads. Dropping markup costs time
23008
- * quadratic in a run of unclosed `<script>`, `<style>` or `<!--` openers, so a
23009
- * very long text could hold the event loop for seconds, and a row that holds
23010
- * no term is checked again on every result while it is in the window. A term
23011
- * past this many characters does not wake.
23012
- */
23013
- const MENTION_TEXT_LIMIT = 16384;
23014
23160
  const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
23015
23161
  function decodeEntities(s) {
23016
23162
  return s.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi, (whole, ref) => {
@@ -23044,6 +23190,14 @@ function readableParts(text) {
23044
23190
  });
23045
23191
  return { visible: decodeEntities(visible), targets };
23046
23192
  }
23193
+ /**
23194
+ * How much of a record's text the word check reads. Dropping markup costs time
23195
+ * quadratic in a run of unclosed `<script>`, `<style>` or `<!--` openers, so a
23196
+ * very long text could hold the event loop for seconds, and a row that holds
23197
+ * no term is checked again on every result while it is in the window. A term
23198
+ * past this many characters does not wake.
23199
+ */
23200
+ const MENTION_TEXT_LIMIT = 16384;
23047
23201
  /**
23048
23202
  * Whether `text` holds one of `terms` as a whole word, case-insensitively:
23049
23203
  * "Data" is in "hi Data!", "@data" and "Data's turn", not in "metadata" or
@@ -23058,7 +23212,9 @@ function readableParts(text) {
23058
23212
  * is how a mention by DID is found when the DID is not in the visible text.
23059
23213
  *
23060
23214
  * The mention query's `contains` matches substrings (model query has no word
23061
- * match); this is the check that keeps "data" from waking on "metadata".
23215
+ * match); this is the check that keeps "data" from waking on "metadata" when
23216
+ * a record is found through its text alone ({@link mentionOf}).
23217
+ *
23062
23218
  * It reads the first {@link MENTION_TEXT_LIMIT} characters only.
23063
23219
  */
23064
23220
  function holdsAWholeWordTerm(text, terms) {
@@ -23072,9 +23228,95 @@ function holdsAWholeWordTerm(text, terms) {
23072
23228
  return new RegExp(`(?<!${WORD_CHAR})${escaped}(?!${WORD_CHAR})`, "iu").test(visible);
23073
23229
  });
23074
23230
  }
23075
- /** The built-in `Container` (`Container.builtinUri`; not imported, so the
23076
- * plugin bundle does not pull in the model layer). */
23077
- const CONTAINER = "ad4m://Container";
23231
+ /** The provenance {@link MentionMessage} carries, from one link. */
23232
+ function provenanceOf(link, via) {
23233
+ const provenance = {
23234
+ verified: link?.proof?.valid === true,
23235
+ via,
23236
+ };
23237
+ if (typeof link?.author === "string")
23238
+ provenance.author = link.author;
23239
+ if (typeof link?.timestamp === "string")
23240
+ provenance.timestamp = link.timestamp;
23241
+ return provenance;
23242
+ }
23243
+ /** The links a model row carries for `key` under `__links`, oldest first. */
23244
+ function rowLinks(row, key) {
23245
+ const links = row?.__links?.[key];
23246
+ return Array.isArray(links) ? links : [];
23247
+ }
23248
+ /** `uri` URI-decoded, or as it is when it is not valid percent-encoding. */
23249
+ function decoded(uri) {
23250
+ try {
23251
+ return decodeURIComponent(uri);
23252
+ }
23253
+ catch {
23254
+ return uri;
23255
+ }
23256
+ }
23257
+ /**
23258
+ * The text a link's target holds, read as the executor reads a string property
23259
+ * (`parse_literal_value`): `literal:string:` decoded, `literal:json:` parsed (a signed
23260
+ * expression to its `data`), any other URI as it is. `undefined` when that is not a string.
23261
+ */
23262
+ function textOf(target) {
23263
+ if (typeof target !== "string")
23264
+ return undefined;
23265
+ if (!target.startsWith("literal:"))
23266
+ return target;
23267
+ const body = target.slice("literal:".length);
23268
+ if (body.startsWith("string:"))
23269
+ return decoded(body.slice("string:".length));
23270
+ if (body.startsWith("json:")) {
23271
+ const json = decoded(body.slice("json:".length));
23272
+ let value;
23273
+ try {
23274
+ value = JSON.parse(json);
23275
+ }
23276
+ catch {
23277
+ return json;
23278
+ }
23279
+ if (value && typeof value === "object" && "data" in value && "author" in value && "proof" in value) {
23280
+ value = value.data;
23281
+ }
23282
+ return typeof value === "string" ? value : undefined;
23283
+ }
23284
+ if (/^(?:number|boolean):/.test(body))
23285
+ return undefined;
23286
+ return target;
23287
+ }
23288
+ /**
23289
+ * Whether a row of one of the mention subscription's two model queries mentions the
23290
+ * subscription's agent, and the provenance of the link it does so in; `null` when it does not.
23291
+ *
23292
+ * - A row of the query over Mentioning: a verified link to the agent's DID that another agent
23293
+ * wrote, in the row's `__links.mentions`. It wakes whatever the record's text says, or
23294
+ * whether it has any: WE's chip label may run into the next word ("@Datai have…"), and a WE
23295
+ * post's mention sits on its root, which has no text. Its provenance is that link's (the
23296
+ * newest such).
23297
+ * - A row of the query over TextContent: the query matched a substring, so the text must hold
23298
+ * a term as a whole word ({@link holdsAWholeWordTerm}), and so must the text of a verified
23299
+ * link another agent wrote, in `__links.text`. Its provenance is that link's (the newest
23300
+ * such). The row's `text` is the newest text link's, whoever wrote it, so it does not say
23301
+ * whose words they are.
23302
+ *
23303
+ * `via` says which it was. A record both queries find wakes once, through the query that
23304
+ * reports it first ({@link WakerSubscriptionManager}).
23305
+ */
23306
+ function mentionOf(row, sub) {
23307
+ const did = sub.did;
23308
+ const byOthers = (links) => links.filter((l) => typeof l.author === "string" && l.author !== did);
23309
+ const linked = byOthers(rowLinks(row, "mentions")).filter((l) => l.data?.target === did && l.proof?.valid === true);
23310
+ if (did && linked.length)
23311
+ return provenanceOf(linked[linked.length - 1], "mentions");
23312
+ const terms = sub.terms ?? [];
23313
+ const names = (text) => typeof text === "string" && holdsAWholeWordTerm(text, terms);
23314
+ const text = Array.isArray(row?.text) ? row.text.join(" ") : row?.text;
23315
+ if (!names(text))
23316
+ return null;
23317
+ const naming = byOthers(rowLinks(row, "text")).filter((l) => l.proof?.valid === true && names(textOf(l.data?.target)));
23318
+ return naming.length ? provenanceOf(naming[naming.length - 1], "text") : null;
23319
+ }
23078
23320
  /**
23079
23321
  * Add a short cause hint to known subscription failures.
23080
23322
  * The executor needs its main key to register a live query; on a restarted
@@ -23084,13 +23326,13 @@ function hintFor(msg) {
23084
23326
  // "Executor is locked" is the current executor's message; "main key not
23085
23327
  // found" is what older executors (and unrelated key lookups) say for the
23086
23328
  // same locked state. Either way the caller cannot fix it themselves: keys
23087
- // live in memory only, so every restart locks the node again and only its
23329
+ // live in memory only, so every restart locks the executor again and only its
23088
23330
  // operator can unlock it.
23089
23331
  if (/executor is locked/i.test(msg) || /main key not found/i.test(msg)) {
23090
- 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";
23332
+ 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";
23091
23333
  }
23092
23334
  if (/timed out after \d+ms/i.test(msg)) {
23093
- 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";
23335
+ 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";
23094
23336
  }
23095
23337
  return "";
23096
23338
  }
@@ -23120,6 +23362,7 @@ async function withTimeout(promise, ms, message) {
23120
23362
  }
23121
23363
  class WakerSubscriptionManager {
23122
23364
  constructor(options) {
23365
+ /** Per subscription its proxies: one, or a mention subscription's text and mention queries. */
23123
23366
  this.proxies = new Map();
23124
23367
  this.activeSubscriptions = new Map();
23125
23368
  /** Subscriptions the executor rejected, waiting to be re-attempted. */
@@ -23189,21 +23432,40 @@ class WakerSubscriptionManager {
23189
23432
  throw new Error("WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options");
23190
23433
  }
23191
23434
  const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;
23192
- if (sub.type === "mention" && sub.className && !sub.terms?.length) {
23193
- // Without terms the whole-word check cannot run, and every substring
23194
- // ("metadata" for "data") would wake the agent.
23195
- throw new Error(`Waker subscription ${sub.id}: a mention subscription needs its terms (get_mention_waker_config returns them)`);
23435
+ if (sub.type === "mention" &&
23436
+ (!sub.className || !sub.terms?.length || !sub.did || !sub.mentionQuery || !sub.mentionClass)) {
23437
+ // Without terms the whole-word check cannot run, so every substring
23438
+ // ("metadata" for "data") would wake the agent; without the DID no link
23439
+ // can be told to be someone else's; without the mention query a mention
23440
+ // link on a record with no text (a WE post's root) never wakes it.
23441
+ 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)`);
23196
23442
  }
23197
23443
  this.logger.info(`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`);
23198
23444
  this.logger.info(`[waker] ${sub.id}: ${sub.className ? `model query over ${sub.className}` : "SPARQL query"}:\n${sub.query}`);
23445
+ if (sub.mentionQuery) {
23446
+ this.logger.info(`[waker] ${sub.id}: model query over ${sub.mentionClass}:\n${sub.mentionQuery}`);
23447
+ }
23199
23448
  const proxy = sub.className
23200
23449
  ? new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient, sub.className)
23201
23450
  : new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
23451
+ const mentionProxy = sub.mentionQuery
23452
+ ? new QuerySubscriptionProxy(sub.perspective, sub.mentionQuery, this.perspectiveClient, sub.mentionClass)
23453
+ : undefined;
23454
+ const proxies = mentionProxy ? [proxy, mentionProxy] : [proxy];
23455
+ const disposeProxies = () => {
23456
+ for (const p of proxies) {
23457
+ try {
23458
+ p.dispose();
23459
+ }
23460
+ catch { }
23461
+ }
23462
+ };
23202
23463
  // Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
23203
23464
  // rejects this promise internally when subscribe() fails, and if nobody catches
23204
23465
  // it before the next microtask it crashes the process.
23205
- if (proxy.initialized && typeof proxy.initialized.catch === "function") {
23206
- proxy.initialized.catch(() => { });
23466
+ for (const p of proxies) {
23467
+ if (p.initialized && typeof p.initialized.catch === "function")
23468
+ p.initialized.catch(() => { });
23207
23469
  }
23208
23470
  // One deadline for the whole handshake: `proxy.subscribe()` and the
23209
23471
  // `initialized` promise it resolves share the budget, so a hang in either
@@ -23214,23 +23476,17 @@ class WakerSubscriptionManager {
23214
23476
  ? withTimeout(step, Math.max(0, budgetMs - (Date.now() - startedAt)), `${what} timed out after ${budgetMs}ms`)
23215
23477
  : step;
23216
23478
  try {
23217
- await bounded(proxy.subscribe(), "subscribe handshake");
23479
+ await bounded(Promise.all(proxies.map((p) => p.subscribe())), "subscribe handshake");
23218
23480
  if (this.isStale(sub.id, token)) {
23219
- try {
23220
- proxy.dispose();
23221
- }
23222
- catch { }
23481
+ disposeProxies();
23223
23482
  return;
23224
23483
  }
23225
- await bounded(proxy.initialized, "subscription initialization");
23484
+ await bounded(Promise.all(proxies.map((p) => p.initialized)), "subscription initialization");
23226
23485
  }
23227
23486
  catch (err) {
23228
23487
  const msg = err?.message ?? String(err);
23229
23488
  this.logger.warn(`[waker] ${sub.id}: subscription failed — ${msg}`);
23230
- try {
23231
- proxy.dispose();
23232
- }
23233
- catch { }
23489
+ disposeProxies();
23234
23490
  // A dispose that landed mid-attempt wins: don't re-queue something the
23235
23491
  // caller has since asked us to forget.
23236
23492
  if (this.isStale(sub.id, token))
@@ -23255,10 +23511,7 @@ class WakerSubscriptionManager {
23255
23511
  : ""));
23256
23512
  }
23257
23513
  if (this.isStale(sub.id, token)) {
23258
- try {
23259
- proxy.dispose();
23260
- }
23261
- catch { }
23514
+ disposeProxies();
23262
23515
  return;
23263
23516
  }
23264
23517
  this.pendingSubscriptions.delete(sub.id);
@@ -23273,8 +23526,9 @@ class WakerSubscriptionManager {
23273
23526
  }
23274
23527
  // `opening` is the result the subscription holds when it opens (`proxy.result`): `onResult`
23275
23528
  // only reports later changes, so this is the one chance to see what was written meanwhile.
23276
- const handleResult = async (result, opening = false) => {
23277
- 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)}`);
23529
+ // `of`: the query the result is from, for the log (a mention subscription has two).
23530
+ const handleResult = async (result, opening = false, of = "") => {
23531
+ 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)}`);
23278
23532
  // A model subscription delivers `{ instances }`, SPARQL an array of
23279
23533
  // rows. Anything else (e.g. `false` on a disconnect/reconnect) is
23280
23534
  // ignored.
@@ -23284,26 +23538,25 @@ class WakerSubscriptionManager {
23284
23538
  return;
23285
23539
  }
23286
23540
  if (sub.type === "mention") {
23287
- // For mention subscriptions: track seen record ids.
23288
- // Only wake for records we haven't seen before.
23541
+ // For mention subscriptions: track seen record ids, across both queries, and wake only
23542
+ // for records not seen before, so a record both find wakes once, through the query that
23543
+ // reports it first.
23289
23544
  const currentSeen = this.seenMessages.get(sub.id) ?? new Set();
23290
23545
  const newMessages = [];
23291
- const terms = sub.terms ?? [];
23546
+ const provenance = new Map();
23292
23547
  for (const item of rows) {
23293
- // A SPARQL row names the record as `source`, a model row as `id`.
23294
- const address = sub.className ? item?.id : item?.source;
23548
+ const address = item?.id;
23295
23549
  if (typeof address !== "string" || !address || currentSeen.has(address))
23296
23550
  continue;
23297
- if (terms.length) {
23298
- // The mention query matched a substring; wake only on a whole word.
23299
- const text = Array.isArray(item.text) ? item.text.join(" ") : item.text;
23300
- if (typeof text !== "string" || !holdsAWholeWordTerm(text, terms)) {
23301
- this.logger.debug(`[waker] ${sub.id}: ${address} holds no term as a whole word, skipping`);
23302
- continue;
23303
- }
23551
+ // A mention link as it is; the text, a whole word only.
23552
+ const mention = mentionOf(item, sub);
23553
+ if (!mention) {
23554
+ this.logger.debug(`[waker] ${sub.id}: ${address} has no verified mention link and no term as a whole word, skipping`);
23555
+ continue;
23304
23556
  }
23305
23557
  currentSeen.add(address);
23306
23558
  newMessages.push(address);
23559
+ provenance.set(address, mention);
23307
23560
  }
23308
23561
  if (newMessages.length === 0) {
23309
23562
  this.logger.info(`[waker] ${sub.id}: no new mention among ${rows.length} items, skipping`);
@@ -23328,7 +23581,7 @@ class WakerSubscriptionManager {
23328
23581
  const ancestors = await this.ancestorsOf(sub, msgAddr, parents);
23329
23582
  this.logger.info(`[waker] ${sub.id}: message ${msgAddr} has ${parents.length} parent(s): ${parents.join(", ")}` +
23330
23583
  (ancestors.length ? `; ancestors: ${ancestors.join(", ")}` : ""));
23331
- mentions.push({ address: msgAddr, parents, ancestors });
23584
+ mentions.push({ address: msgAddr, parents, ancestors, ...provenance.get(msgAddr) });
23332
23585
  }
23333
23586
  this.seenMessages.set(sub.id, currentSeen);
23334
23587
  const pending = this.undelivered.get(sub.id) ?? new Map();
@@ -23354,20 +23607,21 @@ class WakerSubscriptionManager {
23354
23607
  }
23355
23608
  };
23356
23609
  proxy.onResult((result) => handleResult(result));
23610
+ mentionProxy?.onResult((result) => handleResult(result, false, " (mention query)"));
23357
23611
  if (this.isStale(sub.id, token)) {
23358
- try {
23359
- proxy.dispose();
23360
- }
23361
- catch { }
23612
+ disposeProxies();
23362
23613
  return;
23363
23614
  }
23364
- this.proxies.set(sub.id, proxy);
23615
+ this.proxies.set(sub.id, proxies);
23365
23616
  this.activeSubscriptions.set(sub.id, sub);
23366
23617
  // After a restart this wakes on mentions written while the waker was down; on a new
23367
- // subscription it records the existing ones as history.
23368
- if (proxy.result !== undefined) {
23618
+ // subscription it records the existing ones as history. The mention query's first, so a
23619
+ // record both hold wakes through its mention link.
23620
+ for (const [p, of] of [[mentionProxy, " (mention query)"], [proxy, ""]]) {
23621
+ if (p?.result === undefined)
23622
+ continue;
23369
23623
  try {
23370
- await handleResult(proxy.result, true);
23624
+ await handleResult(p.result, true, of);
23371
23625
  }
23372
23626
  catch (e) {
23373
23627
  this.logger.warn(`[waker] ${sub.id}: reading the opening result failed: ${e?.message ?? e}`);
@@ -23430,16 +23684,15 @@ class WakerSubscriptionManager {
23430
23684
  dispose(id, persist = true) {
23431
23685
  // Invalidate any subscribe() for this id that is still awaiting.
23432
23686
  this.generations.set(id, (this.generations.get(id) ?? 0) + 1);
23433
- const proxy = this.proxies.get(id);
23434
- if (proxy) {
23687
+ for (const proxy of this.proxies.get(id) ?? []) {
23435
23688
  try {
23436
23689
  proxy.dispose();
23437
23690
  }
23438
23691
  catch {
23439
23692
  /* ignore */
23440
23693
  }
23441
- this.proxies.delete(id);
23442
23694
  }
23695
+ this.proxies.delete(id);
23443
23696
  const timer = this.debounceTimers.get(id);
23444
23697
  if (timer) {
23445
23698
  clearTimeout(timer);
@@ -24016,4 +24269,4 @@ const SCOPED_EVENTS = new Set([
24016
24269
  "flow-state-changed",
24017
24270
  ]);
24018
24271
 
24019
- export { ACCEPTED_BY_GETTER, AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, AutoProcessorConfig, BelongsToMany, BelongsToOne, CALL_PROTOCOL_VERSION, Capability, CapabilityInput, ComputeLogEntry, Container, DEFAULT_ICE_SERVERS, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, FlowInstance, FlowInstanceRecord, FlowTransitionProposal, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, InterpretationOverlay, InterpretationRun, LONG_METHODS, LONG_TIMEOUT_MS, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LiveQuery, LocalModel, LocalModelInput, MENTION_TEXT_LIMIT, MeshManager, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PROPOSER_GETTER, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, READ_METHODS, ReadOnly, Resource, ResourceInput, RpcError, RuntimeInfo, SCOPED_EVENTS, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TextContent, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, applyUpdate, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, createTelepresenceChannel, determineNamespace, determinePredicate, effectiveLiteralStorage, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, hintFor, holdsAWholeWordTerm, ifExpr, invalidatePerspectiveCache, isArrayType, isContainedScope, isContainmentTraversal, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, isTraverseScope, linkEqual, linkExpressionInputToWire, linkExpressionToWire, linkMutationsToWire, literal, looksLikeUri, neighbourhoodExpressionFromWire, normalizeNamespaceString, normalizeSchemaType, normalizeValue, normalizeWhereForSparql, parseCallMessage, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, requireSingleParent, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString, valueToLiteralIri };
24272
+ export { ACCEPTED_BY_GETTER, AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, AutoProcessorConfig, BelongsToMany, BelongsToOne, CALL_PROTOCOL_VERSION, Capability, CapabilityInput, ComputeLogEntry, Container, DEFAULT_ICE_SERVERS, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, FlowInstance, FlowInstanceRecord, FlowTransitionProposal, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, InterpretationOverlay, InterpretationRun, LONG_METHODS, LONG_TIMEOUT_MS, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LiveQuery, LocalModel, LocalModelInput, MENTION_TEXT_LIMIT, Mentioning, MeshManager, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PROPOSER_GETTER, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, READ_METHODS, ReadOnly, Resource, ResourceInput, RpcError, RuntimeInfo, SCOPED_EVENTS, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TextContent, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, applyUpdate, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, createTelepresenceChannel, determineNamespace, determinePredicate, effectiveLiteralStorage, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, hintFor, holdsAWholeWordTerm, ifExpr, invalidatePerspectiveCache, isArrayType, isContainedScope, isContainmentTraversal, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, isTraverseScope, linkEqual, linkExpressionInputToWire, linkExpressionToWire, linkMutationsToWire, literal, looksLikeUri, mentionOf, neighbourhoodExpressionFromWire, normalizeNamespaceString, normalizeSchemaType, normalizeValue, normalizeWhereForSparql, parseCallMessage, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, requireSingleParent, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString, valueToLiteralIri };