@coasys/ad4m 0.13.1-staging.4 → 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 (43) hide show
  1. package/lib/index.cjs +387 -154
  2. package/lib/index.js +387 -155
  3. package/lib/src/generated/api/AgentMessage.d.ts +10 -0
  4. package/lib/src/generated/api/AgentMessage.js +2 -0
  5. package/lib/src/generated/api/AgentReply.d.ts +9 -0
  6. package/lib/src/generated/api/AgentReply.js +2 -0
  7. package/lib/src/generated/api/RpcMethods.d.ts +6 -0
  8. package/lib/src/generated/api/RpcMethods.js +1 -0
  9. package/lib/src/generated/api/RunAgentRequest.d.ts +26 -0
  10. package/lib/src/generated/api/RunAgentRequest.js +1 -0
  11. package/lib/src/generated/api/index.d.ts +3 -0
  12. package/lib/src/index.d.ts +1 -0
  13. package/lib/src/index.js +1 -0
  14. package/lib/src/model/types.d.ts +6 -0
  15. package/lib/src/neighbourhood/SfuManager.d.ts +15 -0
  16. package/lib/src/neighbourhood/SfuManager.js +39 -2
  17. package/lib/src/perspectives/Mentioning.d.ts +37 -0
  18. package/lib/src/perspectives/Mentioning.js +58 -0
  19. package/lib/src/perspectives/PerspectiveClient.d.ts +22 -0
  20. package/lib/src/perspectives/PerspectiveClient.js +13 -0
  21. package/lib/src/perspectives/PerspectiveProxy.d.ts +19 -0
  22. package/lib/src/perspectives/PerspectiveProxy.js +19 -0
  23. package/lib/src/perspectives/TextContent.d.ts +4 -0
  24. package/lib/src/perspectives/TextContent.js +4 -0
  25. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +69 -10
  26. package/lib/src/perspectives/WakerSubscriptionManager.js +160 -58
  27. package/package.json +2 -2
  28. package/src/generated/api/AgentMessage.ts +10 -0
  29. package/src/generated/api/AgentReply.ts +10 -0
  30. package/src/generated/api/RpcMethods.ts +4 -0
  31. package/src/generated/api/RunAgentRequest.ts +26 -0
  32. package/src/generated/api/index.ts +3 -0
  33. package/src/index.ts +1 -0
  34. package/src/model/types.ts +6 -0
  35. package/src/neighbourhood/SfuManager.test.ts +151 -2
  36. package/src/neighbourhood/SfuManager.ts +38 -1
  37. package/src/perspectives/Mentioning.test.ts +78 -0
  38. package/src/perspectives/Mentioning.ts +42 -0
  39. package/src/perspectives/PerspectiveClient.ts +30 -0
  40. package/src/perspectives/PerspectiveProxy.ts +26 -0
  41. package/src/perspectives/TextContent.ts +4 -0
  42. package/src/perspectives/WakerSubscriptionManager.test.ts +383 -151
  43. package/src/perspectives/WakerSubscriptionManager.ts +217 -58
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",
@@ -1845,6 +1846,8 @@ class SfuManager {
1845
1846
  this.rosterUnsubscribe = null;
1846
1847
  this.dataChannelUnsubscribe = null;
1847
1848
  this.disconnectedTimer = null;
1849
+ /** Running while the room's roster leaves this agent out: see `noticeRoster`. */
1850
+ this.unlistedTimer = null;
1848
1851
  this.neighbourhood = neighbourhood;
1849
1852
  this.neighbourhoodUrl = neighbourhoodUrl || "";
1850
1853
  this.roomId = roomId;
@@ -2131,6 +2134,37 @@ class SfuManager {
2131
2134
  this.renegotiationUnsubscribe = null;
2132
2135
  this.rosterUnsubscribe?.();
2133
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);
2134
2168
  }
2135
2169
  /** Undo a join that failed part way: its subscription and its connection. */
2136
2170
  abandon(pc) {
@@ -2165,8 +2199,10 @@ class SfuManager {
2165
2199
  if (!ours(roster) || this.state.peerConnection !== pc)
2166
2200
  return;
2167
2201
  void joined.then(() => {
2168
- if (this.state.peerConnection === pc)
2169
- 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);
2170
2206
  });
2171
2207
  });
2172
2208
  for (const unsubscribe of previous)
@@ -2380,6 +2416,8 @@ SfuManager.MAX_RECONNECTS = 3;
2380
2416
  SfuManager.REJOIN_WINDOW_MS = 120000;
2381
2417
  /** How long ICE may stay disconnected before a rebuild: the executor's `ICE_DISCONNECT_GRACE`. */
2382
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;
2383
2421
 
2384
2422
  /**
2385
2423
  * Peer-to-peer WebRTC mesh transport for the AD4M SDK Session interface.
@@ -7883,6 +7921,19 @@ class PerspectiveProxy {
7883
7921
  observationId, emitDebugEvents, options) {
7884
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);
7885
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
+ }
7886
7937
  /**
7887
7938
  * Register a neighbourhood auto-processor on this perspective. The executor
7888
7939
  * then runs interpretation automatically over new source items (like Flux
@@ -8257,6 +8308,12 @@ class PerspectiveProxy {
8257
8308
  /**
8258
8309
  * Adds a pre-signed LinkExpression to the perspective.
8259
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
+ *
8260
8317
  * @param link - The signed LinkExpression to add
8261
8318
  * @param status - Whether the link should be shared
8262
8319
  * @param batchId - Optional batch ID to group this operation with others
@@ -9773,6 +9830,19 @@ class PerspectiveClient {
9773
9830
  emitDebugEvents,
9774
9831
  }, options);
9775
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
+ }
9776
9846
  /**
9777
9847
  * Register a neighbourhood auto-processor on this perspective. The executor's
9778
9848
  * watch loop then runs interpretation automatically over new source items
@@ -21839,13 +21909,13 @@ class LanguageLanguageInput {
21839
21909
  * const runs = await InterpretationRun.findAll(perspective);
21840
21910
  * const configs = await AutoProcessorConfig.findAll(perspective);
21841
21911
  */
21842
- var __decorate$3 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
21912
+ var __decorate$4 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
21843
21913
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
21844
21914
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21845
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;
21846
21916
  return c > 3 && r && Object.defineProperty(target, key, r), r;
21847
21917
  };
21848
- var __metadata$3 = (undefined && undefined.__metadata) || function (k, v) {
21918
+ var __metadata$4 = (undefined && undefined.__metadata) || function (k, v) {
21849
21919
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
21850
21920
  };
21851
21921
  // ── AutoProcessorConfig ─────────────────────────────────────────────────────
@@ -21886,71 +21956,71 @@ exports.AutoProcessorConfig = class AutoProcessorConfig extends Ad4mModel {
21886
21956
  // `batchMax` + `claimTtlMs` — the Rust SDNA takes the same shape.
21887
21957
  }
21888
21958
  };
21889
- __decorate$3([
21959
+ __decorate$4([
21890
21960
  Property({ through: "ad4m://processor_id", required: true, identity: true }),
21891
- __metadata$3("design:type", String)
21961
+ __metadata$4("design:type", String)
21892
21962
  ], exports.AutoProcessorConfig.prototype, "processorId", void 0);
21893
- __decorate$3([
21963
+ __decorate$4([
21894
21964
  Property({ through: "ad4m://source_scope_query", required: true }),
21895
- __metadata$3("design:type", String)
21965
+ __metadata$4("design:type", String)
21896
21966
  ], exports.AutoProcessorConfig.prototype, "sourceScopeQuery", void 0);
21897
- __decorate$3([
21967
+ __decorate$4([
21898
21968
  Optional({ through: "ad4m://base_prefix" }),
21899
- __metadata$3("design:type", String)
21969
+ __metadata$4("design:type", String)
21900
21970
  ], exports.AutoProcessorConfig.prototype, "basePrefix", void 0);
21901
- __decorate$3([
21971
+ __decorate$4([
21902
21972
  HasMany({ through: "ad4m://interpretation_class", datatype: "xsd:string" }),
21903
- __metadata$3("design:type", Array)
21973
+ __metadata$4("design:type", Array)
21904
21974
  ], exports.AutoProcessorConfig.prototype, "interpretationClasses", void 0);
21905
- __decorate$3([
21975
+ __decorate$4([
21906
21976
  HasMany({ through: "ad4m://flow", datatype: "xsd:string" }),
21907
- __metadata$3("design:type", Array)
21977
+ __metadata$4("design:type", Array)
21908
21978
  ], exports.AutoProcessorConfig.prototype, "flows", void 0);
21909
- __decorate$3([
21979
+ __decorate$4([
21910
21980
  Property({ through: "ad4m://debounce_ms", required: true }),
21911
- __metadata$3("design:type", String)
21981
+ __metadata$4("design:type", String)
21912
21982
  ], exports.AutoProcessorConfig.prototype, "debounceMs", void 0);
21913
- __decorate$3([
21983
+ __decorate$4([
21914
21984
  Optional({ through: "ad4m://batch_min" }),
21915
- __metadata$3("design:type", String)
21985
+ __metadata$4("design:type", String)
21916
21986
  ], exports.AutoProcessorConfig.prototype, "batchMin", void 0);
21917
- __decorate$3([
21987
+ __decorate$4([
21918
21988
  Property({ through: "ad4m://batch_max", required: true }),
21919
- __metadata$3("design:type", String)
21989
+ __metadata$4("design:type", String)
21920
21990
  ], exports.AutoProcessorConfig.prototype, "batchMax", void 0);
21921
- __decorate$3([
21991
+ __decorate$4([
21922
21992
  Optional({ through: "ad4m://max_wait_ms" }),
21923
- __metadata$3("design:type", String)
21993
+ __metadata$4("design:type", String)
21924
21994
  ], exports.AutoProcessorConfig.prototype, "maxWaitMs", void 0);
21925
- __decorate$3([
21995
+ __decorate$4([
21926
21996
  Property({ through: "ad4m://claim_ttl_ms", required: true }),
21927
- __metadata$3("design:type", String)
21997
+ __metadata$4("design:type", String)
21928
21998
  ], exports.AutoProcessorConfig.prototype, "claimTtlMs", void 0);
21929
- __decorate$3([
21999
+ __decorate$4([
21930
22000
  Optional({ through: "ad4m://source_window_ms" }),
21931
- __metadata$3("design:type", String)
22001
+ __metadata$4("design:type", String)
21932
22002
  ], exports.AutoProcessorConfig.prototype, "sourceWindowMs", void 0);
21933
- __decorate$3([
22003
+ __decorate$4([
21934
22004
  Optional({ through: "ad4m://dedup_strategy" }),
21935
- __metadata$3("design:type", String)
22005
+ __metadata$4("design:type", String)
21936
22006
  ], exports.AutoProcessorConfig.prototype, "dedupStrategy", void 0);
21937
- __decorate$3([
22007
+ __decorate$4([
21938
22008
  Optional({ through: "ad4m://existing_scope" }),
21939
- __metadata$3("design:type", String)
22009
+ __metadata$4("design:type", String)
21940
22010
  ], exports.AutoProcessorConfig.prototype, "existingScope", void 0);
21941
- __decorate$3([
22011
+ __decorate$4([
21942
22012
  Optional({ through: "ad4m://mint_scope" }),
21943
- __metadata$3("design:type", String)
22013
+ __metadata$4("design:type", String)
21944
22014
  ], exports.AutoProcessorConfig.prototype, "mintScope", void 0);
21945
- __decorate$3([
22015
+ __decorate$4([
21946
22016
  Optional({ through: "ad4m://max_tool_calls" }),
21947
- __metadata$3("design:type", String)
22017
+ __metadata$4("design:type", String)
21948
22018
  ], exports.AutoProcessorConfig.prototype, "maxToolCalls", void 0);
21949
- __decorate$3([
22019
+ __decorate$4([
21950
22020
  Optional({ through: "ad4m://emit_debug_events", resolveLanguage: "literal" }),
21951
- __metadata$3("design:type", String)
22021
+ __metadata$4("design:type", String)
21952
22022
  ], exports.AutoProcessorConfig.prototype, "emitDebugEvents", void 0);
21953
- exports.AutoProcessorConfig = __decorate$3([
22023
+ exports.AutoProcessorConfig = __decorate$4([
21954
22024
  Model$1({ name: "AutoProcessor" })
21955
22025
  ], exports.AutoProcessorConfig);
21956
22026
  // ── InterpretationRun ───────────────────────────────────────────────────────
@@ -21974,39 +22044,39 @@ exports.InterpretationRun = class InterpretationRun extends Ad4mModel {
21974
22044
  this.sources = [];
21975
22045
  }
21976
22046
  };
21977
- __decorate$3([
22047
+ __decorate$4([
21978
22048
  Property({ through: "ad4m://interp/run_id", required: true, identity: true }),
21979
- __metadata$3("design:type", String)
22049
+ __metadata$4("design:type", String)
21980
22050
  ], exports.InterpretationRun.prototype, "runId", void 0);
21981
- __decorate$3([
22051
+ __decorate$4([
21982
22052
  Optional({ through: "ad4m://interp/model" }),
21983
- __metadata$3("design:type", String)
22053
+ __metadata$4("design:type", String)
21984
22054
  ], exports.InterpretationRun.prototype, "model", void 0);
21985
- __decorate$3([
22055
+ __decorate$4([
21986
22056
  Optional({ through: "ad4m://interp/prompt_version" }),
21987
- __metadata$3("design:type", String)
22057
+ __metadata$4("design:type", String)
21988
22058
  ], exports.InterpretationRun.prototype, "promptVersion", void 0);
21989
- __decorate$3([
22059
+ __decorate$4([
21990
22060
  Optional({ through: "ad4m://interp/ran_at" }),
21991
- __metadata$3("design:type", String)
22061
+ __metadata$4("design:type", String)
21992
22062
  ], exports.InterpretationRun.prototype, "ranAt", void 0);
21993
- __decorate$3([
22063
+ __decorate$4([
21994
22064
  Optional({ through: "ad4m://interp/processor" }),
21995
- __metadata$3("design:type", String)
22065
+ __metadata$4("design:type", String)
21996
22066
  ], exports.InterpretationRun.prototype, "processor", void 0);
21997
- __decorate$3([
22067
+ __decorate$4([
21998
22068
  HasMany({ through: "ad4m://interp/sources", datatype: "xsd:string" }),
21999
- __metadata$3("design:type", Array)
22069
+ __metadata$4("design:type", Array)
22000
22070
  ], exports.InterpretationRun.prototype, "sources", void 0);
22001
- __decorate$3([
22071
+ __decorate$4([
22002
22072
  Optional({ through: "ad4m://interp/debug_prompt", resolveLanguage: "literal" }),
22003
- __metadata$3("design:type", String)
22073
+ __metadata$4("design:type", String)
22004
22074
  ], exports.InterpretationRun.prototype, "debugPrompt", void 0);
22005
- __decorate$3([
22075
+ __decorate$4([
22006
22076
  Optional({ through: "ad4m://interp/debug_response", resolveLanguage: "literal" }),
22007
- __metadata$3("design:type", String)
22077
+ __metadata$4("design:type", String)
22008
22078
  ], exports.InterpretationRun.prototype, "debugResponse", void 0);
22009
- exports.InterpretationRun = __decorate$3([
22079
+ exports.InterpretationRun = __decorate$4([
22010
22080
  Model$1({ name: "InterpretationRun" })
22011
22081
  ], exports.InterpretationRun);
22012
22082
  // ── InterpretationOverlay ───────────────────────────────────────────────────
@@ -22036,15 +22106,15 @@ exports.InterpretationOverlay = class InterpretationOverlay extends Ad4mModel {
22036
22106
  this.kind = "";
22037
22107
  }
22038
22108
  };
22039
- __decorate$3([
22109
+ __decorate$4([
22040
22110
  Property({ through: "ad4m://interp/kind", required: true }),
22041
- __metadata$3("design:type", String)
22111
+ __metadata$4("design:type", String)
22042
22112
  ], exports.InterpretationOverlay.prototype, "kind", void 0);
22043
- __decorate$3([
22113
+ __decorate$4([
22044
22114
  Optional({ through: "ad4m://interp/run" }),
22045
- __metadata$3("design:type", String)
22115
+ __metadata$4("design:type", String)
22046
22116
  ], exports.InterpretationOverlay.prototype, "run", void 0);
22047
- exports.InterpretationOverlay = __decorate$3([
22117
+ exports.InterpretationOverlay = __decorate$4([
22048
22118
  Model$1({ name: "InterpretationOverlay" })
22049
22119
  ], exports.InterpretationOverlay);
22050
22120
 
@@ -22068,13 +22138,13 @@ exports.InterpretationOverlay = __decorate$3([
22068
22138
  * - the SDNA-parity test locks TS/Rust drift against
22069
22139
  * `rust-executor/src/perspectives/hardwired_sdna/flow_transition_proposal.json`.
22070
22140
  */
22071
- var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22141
+ var __decorate$3 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22072
22142
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22073
22143
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22074
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;
22075
22145
  return c > 3 && r && Object.defineProperty(target, key, r), r;
22076
22146
  };
22077
- var __metadata$2 = (undefined && undefined.__metadata) || function (k, v) {
22147
+ var __metadata$3 = (undefined && undefined.__metadata) || function (k, v) {
22078
22148
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22079
22149
  };
22080
22150
  /**
@@ -22181,55 +22251,55 @@ exports.FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel
22181
22251
  // of the proposal's own links (all written together during create_subject).
22182
22252
  }
22183
22253
  };
22184
- __decorate$2([
22254
+ __decorate$3([
22185
22255
  Property({ through: "ad4m://flow/instance", required: true, identity: true }),
22186
- __metadata$2("design:type", String)
22256
+ __metadata$3("design:type", String)
22187
22257
  ], exports.FlowTransitionProposal.prototype, "flowInstance", void 0);
22188
- __decorate$2([
22258
+ __decorate$3([
22189
22259
  Property({ through: "ad4m://flow/from_state", required: true }),
22190
- __metadata$2("design:type", String)
22260
+ __metadata$3("design:type", String)
22191
22261
  ], exports.FlowTransitionProposal.prototype, "fromState", void 0);
22192
- __decorate$2([
22262
+ __decorate$3([
22193
22263
  Property({ through: "ad4m://flow/to_state", required: true }),
22194
- __metadata$2("design:type", String)
22264
+ __metadata$3("design:type", String)
22195
22265
  ], exports.FlowTransitionProposal.prototype, "toState", void 0);
22196
- __decorate$2([
22266
+ __decorate$3([
22197
22267
  Property({ through: "ad4m://flow/proposer", required: true, getter: PROPOSER_GETTER, datatype: "xsd:string" }),
22198
- __metadata$2("design:type", String)
22268
+ __metadata$3("design:type", String)
22199
22269
  ], exports.FlowTransitionProposal.prototype, "proposer", void 0);
22200
- __decorate$2([
22270
+ __decorate$3([
22201
22271
  HasMany({ through: "ad4m://flow/evidence", datatype: "xsd:string" }),
22202
- __metadata$2("design:type", Array)
22272
+ __metadata$3("design:type", Array)
22203
22273
  ], exports.FlowTransitionProposal.prototype, "evidence", void 0);
22204
- __decorate$2([
22274
+ __decorate$3([
22205
22275
  Property({ through: "ad4m://flow/evidence_hashes", required: true }),
22206
- __metadata$2("design:type", String)
22276
+ __metadata$3("design:type", String)
22207
22277
  ], exports.FlowTransitionProposal.prototype, "evidenceHashes", void 0);
22208
- __decorate$2([
22278
+ __decorate$3([
22209
22279
  HasMany({ through: "ad4m://flow/output", datatype: "xsd:string" }),
22210
- __metadata$2("design:type", Array)
22280
+ __metadata$3("design:type", Array)
22211
22281
  ], exports.FlowTransitionProposal.prototype, "outputs", void 0);
22212
- __decorate$2([
22282
+ __decorate$3([
22213
22283
  Property({ through: "ad4m://flow/outputs_hash" }),
22214
- __metadata$2("design:type", String)
22284
+ __metadata$3("design:type", String)
22215
22285
  ], exports.FlowTransitionProposal.prototype, "outputsHash", void 0);
22216
- __decorate$2([
22286
+ __decorate$3([
22217
22287
  Property({ through: "ad4m://flow/nonce" }),
22218
- __metadata$2("design:type", String)
22288
+ __metadata$3("design:type", String)
22219
22289
  ], exports.FlowTransitionProposal.prototype, "nonce", void 0);
22220
- __decorate$2([
22290
+ __decorate$3([
22221
22291
  Optional({ through: "ad4m://flow/run_uri" }),
22222
- __metadata$2("design:type", String)
22292
+ __metadata$3("design:type", String)
22223
22293
  ], exports.FlowTransitionProposal.prototype, "runUri", void 0);
22224
- __decorate$2([
22294
+ __decorate$3([
22225
22295
  Optional({ through: "ad4m://flow/rationale" }),
22226
- __metadata$2("design:type", String)
22296
+ __metadata$3("design:type", String)
22227
22297
  ], exports.FlowTransitionProposal.prototype, "rationale", void 0);
22228
- __decorate$2([
22298
+ __decorate$3([
22229
22299
  HasMany({ through: "ad4m://acceptedBy", getter: ACCEPTED_BY_GETTER, readOnly: true }),
22230
- __metadata$2("design:type", Array)
22300
+ __metadata$3("design:type", Array)
22231
22301
  ], exports.FlowTransitionProposal.prototype, "acceptedBy", void 0);
22232
- exports.FlowTransitionProposal = __decorate$2([
22302
+ exports.FlowTransitionProposal = __decorate$3([
22233
22303
  Model$1({ name: "FlowTransitionProposal" })
22234
22304
  ], exports.FlowTransitionProposal);
22235
22305
  // ── FlowInstanceRecord ──────────────────────────────────────────────────────
@@ -22289,25 +22359,25 @@ exports.FlowInstanceRecord = class FlowInstanceRecord extends Ad4mModel {
22289
22359
  // of the instance's own links (all written together during `mint_flow_instance`).
22290
22360
  }
22291
22361
  };
22292
- __decorate$2([
22362
+ __decorate$3([
22293
22363
  Property({ through: "ad4m://flow/flow_uri", required: true, identity: true }),
22294
- __metadata$2("design:type", String)
22364
+ __metadata$3("design:type", String)
22295
22365
  ], exports.FlowInstanceRecord.prototype, "flowUri", void 0);
22296
- __decorate$2([
22366
+ __decorate$3([
22297
22367
  Property({ through: "ad4m://flow/base", required: true }),
22298
- __metadata$2("design:type", String)
22368
+ __metadata$3("design:type", String)
22299
22369
  ], exports.FlowInstanceRecord.prototype, "subject", void 0);
22300
- exports.FlowInstanceRecord = __decorate$2([
22370
+ exports.FlowInstanceRecord = __decorate$3([
22301
22371
  Model$1({ name: "FlowInstance" })
22302
22372
  ], exports.FlowInstanceRecord);
22303
22373
 
22304
- var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22374
+ var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22305
22375
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22306
22376
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22307
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;
22308
22378
  return c > 3 && r && Object.defineProperty(target, key, r), r;
22309
22379
  };
22310
- var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22380
+ var __metadata$2 = (undefined && undefined.__metadata) || function (k, v) {
22311
22381
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22312
22382
  };
22313
22383
  /**
@@ -22333,6 +22403,10 @@ var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22333
22403
  * reads it by its URI, `ad4m://TextContent`, so a perspective never stores it
22334
22404
  * and an app class named `TextContent` does not replace it. `register()` on
22335
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.
22336
22410
  */
22337
22411
  exports.TextContent = class TextContent extends Ad4mModel {
22338
22412
  constructor() {
@@ -22343,14 +22417,70 @@ exports.TextContent = class TextContent extends Ad4mModel {
22343
22417
  };
22344
22418
  /** The URI the executor reads it by. */
22345
22419
  exports.TextContent.builtinUri = "ad4m://TextContent";
22346
- __decorate$1([
22420
+ __decorate$2([
22347
22421
  Property({ through: "ad4m://text" }),
22348
- __metadata$1("design:type", String)
22422
+ __metadata$2("design:type", String)
22349
22423
  ], exports.TextContent.prototype, "text", void 0);
22350
- exports.TextContent = __decorate$1([
22424
+ exports.TextContent = __decorate$2([
22351
22425
  Model$1({ name: "TextContent", abstract: true })
22352
22426
  ], exports.TextContent);
22353
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
+
22354
22484
  var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22355
22485
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22356
22486
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -22999,6 +23129,9 @@ function parseLitBoolean(val) {
22999
23129
  * module (`plugins/ad4m/wakerSubscriptionManager.ts`) rather than carrying its
23000
23130
  * own copy. Any behaviour change belongs here.
23001
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";
23002
23135
  /** A letter, combining mark, digit or underscore: what a term must not touch. */
23003
23136
  const WORD_CHAR = "[\\p{L}\\p{M}\\p{N}_]";
23004
23137
  /**
@@ -23028,14 +23161,6 @@ const BREAKING_TAG = /^<\/?(?:p|div|br|hr|li|ul|ol|h[1-6]|blockquote|pre|tr|td|t
23028
23161
  */
23029
23162
  const ATTRIBUTES = new RegExp(ATTRIBUTE, "g");
23030
23163
  const MENTION_TARGET = /^\s+(?:href|data-id|data-did)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))$/i;
23031
- /**
23032
- * How much of a record's text the word check reads. Dropping markup costs time
23033
- * quadratic in a run of unclosed `<script>`, `<style>` or `<!--` openers, so a
23034
- * very long text could hold the event loop for seconds, and a row that holds
23035
- * no term is checked again on every result while it is in the window. A term
23036
- * past this many characters does not wake.
23037
- */
23038
- const MENTION_TEXT_LIMIT = 16384;
23039
23164
  const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
23040
23165
  function decodeEntities(s) {
23041
23166
  return s.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi, (whole, ref) => {
@@ -23069,6 +23194,14 @@ function readableParts(text) {
23069
23194
  });
23070
23195
  return { visible: decodeEntities(visible), targets };
23071
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;
23072
23205
  /**
23073
23206
  * Whether `text` holds one of `terms` as a whole word, case-insensitively:
23074
23207
  * "Data" is in "hi Data!", "@data" and "Data's turn", not in "metadata" or
@@ -23083,7 +23216,9 @@ function readableParts(text) {
23083
23216
  * is how a mention by DID is found when the DID is not in the visible text.
23084
23217
  *
23085
23218
  * The mention query's `contains` matches substrings (model query has no word
23086
- * match); this is the check that keeps "data" from waking on "metadata".
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
+ *
23087
23222
  * It reads the first {@link MENTION_TEXT_LIMIT} characters only.
23088
23223
  */
23089
23224
  function holdsAWholeWordTerm(text, terms) {
@@ -23097,9 +23232,95 @@ function holdsAWholeWordTerm(text, terms) {
23097
23232
  return new RegExp(`(?<!${WORD_CHAR})${escaped}(?!${WORD_CHAR})`, "iu").test(visible);
23098
23233
  });
23099
23234
  }
23100
- /** The built-in `Container` (`Container.builtinUri`; not imported, so the
23101
- * plugin bundle does not pull in the model layer). */
23102
- const CONTAINER = "ad4m://Container";
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
+ }
23103
23324
  /**
23104
23325
  * Add a short cause hint to known subscription failures.
23105
23326
  * The executor needs its main key to register a live query; on a restarted
@@ -23145,6 +23366,7 @@ async function withTimeout(promise, ms, message) {
23145
23366
  }
23146
23367
  class WakerSubscriptionManager {
23147
23368
  constructor(options) {
23369
+ /** Per subscription its proxies: one, or a mention subscription's text and mention queries. */
23148
23370
  this.proxies = new Map();
23149
23371
  this.activeSubscriptions = new Map();
23150
23372
  /** Subscriptions the executor rejected, waiting to be re-attempted. */
@@ -23214,21 +23436,40 @@ class WakerSubscriptionManager {
23214
23436
  throw new Error("WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options");
23215
23437
  }
23216
23438
  const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;
23217
- if (sub.type === "mention" && sub.className && !sub.terms?.length) {
23218
- // Without terms the whole-word check cannot run, and every substring
23219
- // ("metadata" for "data") would wake the agent.
23220
- throw new Error(`Waker subscription ${sub.id}: a mention subscription needs its terms (get_mention_waker_config returns them)`);
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)`);
23221
23446
  }
23222
23447
  this.logger.info(`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`);
23223
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
+ }
23224
23452
  const proxy = sub.className
23225
23453
  ? new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient, sub.className)
23226
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
+ };
23227
23467
  // Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
23228
23468
  // rejects this promise internally when subscribe() fails, and if nobody catches
23229
23469
  // it before the next microtask it crashes the process.
23230
- if (proxy.initialized && typeof proxy.initialized.catch === "function") {
23231
- proxy.initialized.catch(() => { });
23470
+ for (const p of proxies) {
23471
+ if (p.initialized && typeof p.initialized.catch === "function")
23472
+ p.initialized.catch(() => { });
23232
23473
  }
23233
23474
  // One deadline for the whole handshake: `proxy.subscribe()` and the
23234
23475
  // `initialized` promise it resolves share the budget, so a hang in either
@@ -23239,23 +23480,17 @@ class WakerSubscriptionManager {
23239
23480
  ? withTimeout(step, Math.max(0, budgetMs - (Date.now() - startedAt)), `${what} timed out after ${budgetMs}ms`)
23240
23481
  : step;
23241
23482
  try {
23242
- await bounded(proxy.subscribe(), "subscribe handshake");
23483
+ await bounded(Promise.all(proxies.map((p) => p.subscribe())), "subscribe handshake");
23243
23484
  if (this.isStale(sub.id, token)) {
23244
- try {
23245
- proxy.dispose();
23246
- }
23247
- catch { }
23485
+ disposeProxies();
23248
23486
  return;
23249
23487
  }
23250
- await bounded(proxy.initialized, "subscription initialization");
23488
+ await bounded(Promise.all(proxies.map((p) => p.initialized)), "subscription initialization");
23251
23489
  }
23252
23490
  catch (err) {
23253
23491
  const msg = err?.message ?? String(err);
23254
23492
  this.logger.warn(`[waker] ${sub.id}: subscription failed — ${msg}`);
23255
- try {
23256
- proxy.dispose();
23257
- }
23258
- catch { }
23493
+ disposeProxies();
23259
23494
  // A dispose that landed mid-attempt wins: don't re-queue something the
23260
23495
  // caller has since asked us to forget.
23261
23496
  if (this.isStale(sub.id, token))
@@ -23280,10 +23515,7 @@ class WakerSubscriptionManager {
23280
23515
  : ""));
23281
23516
  }
23282
23517
  if (this.isStale(sub.id, token)) {
23283
- try {
23284
- proxy.dispose();
23285
- }
23286
- catch { }
23518
+ disposeProxies();
23287
23519
  return;
23288
23520
  }
23289
23521
  this.pendingSubscriptions.delete(sub.id);
@@ -23298,8 +23530,9 @@ class WakerSubscriptionManager {
23298
23530
  }
23299
23531
  // `opening` is the result the subscription holds when it opens (`proxy.result`): `onResult`
23300
23532
  // only reports later changes, so this is the one chance to see what was written meanwhile.
23301
- const handleResult = async (result, opening = false) => {
23302
- this.logger.info(`[waker] ${sub.id}: ${opening ? "opening result" : "onResult fired"} — type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);
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)}`);
23303
23536
  // A model subscription delivers `{ instances }`, SPARQL an array of
23304
23537
  // rows. Anything else (e.g. `false` on a disconnect/reconnect) is
23305
23538
  // ignored.
@@ -23309,26 +23542,25 @@ class WakerSubscriptionManager {
23309
23542
  return;
23310
23543
  }
23311
23544
  if (sub.type === "mention") {
23312
- // For mention subscriptions: track seen record ids.
23313
- // 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.
23314
23548
  const currentSeen = this.seenMessages.get(sub.id) ?? new Set();
23315
23549
  const newMessages = [];
23316
- const terms = sub.terms ?? [];
23550
+ const provenance = new Map();
23317
23551
  for (const item of rows) {
23318
- // A SPARQL row names the record as `source`, a model row as `id`.
23319
- const address = sub.className ? item?.id : item?.source;
23552
+ const address = item?.id;
23320
23553
  if (typeof address !== "string" || !address || currentSeen.has(address))
23321
23554
  continue;
23322
- if (terms.length) {
23323
- // The mention query matched a substring; wake only on a whole word.
23324
- const text = Array.isArray(item.text) ? item.text.join(" ") : item.text;
23325
- if (typeof text !== "string" || !holdsAWholeWordTerm(text, terms)) {
23326
- this.logger.debug(`[waker] ${sub.id}: ${address} holds no term as a whole word, skipping`);
23327
- continue;
23328
- }
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;
23329
23560
  }
23330
23561
  currentSeen.add(address);
23331
23562
  newMessages.push(address);
23563
+ provenance.set(address, mention);
23332
23564
  }
23333
23565
  if (newMessages.length === 0) {
23334
23566
  this.logger.info(`[waker] ${sub.id}: no new mention among ${rows.length} items, skipping`);
@@ -23353,7 +23585,7 @@ class WakerSubscriptionManager {
23353
23585
  const ancestors = await this.ancestorsOf(sub, msgAddr, parents);
23354
23586
  this.logger.info(`[waker] ${sub.id}: message ${msgAddr} has ${parents.length} parent(s): ${parents.join(", ")}` +
23355
23587
  (ancestors.length ? `; ancestors: ${ancestors.join(", ")}` : ""));
23356
- mentions.push({ address: msgAddr, parents, ancestors });
23588
+ mentions.push({ address: msgAddr, parents, ancestors, ...provenance.get(msgAddr) });
23357
23589
  }
23358
23590
  this.seenMessages.set(sub.id, currentSeen);
23359
23591
  const pending = this.undelivered.get(sub.id) ?? new Map();
@@ -23379,20 +23611,21 @@ class WakerSubscriptionManager {
23379
23611
  }
23380
23612
  };
23381
23613
  proxy.onResult((result) => handleResult(result));
23614
+ mentionProxy?.onResult((result) => handleResult(result, false, " (mention query)"));
23382
23615
  if (this.isStale(sub.id, token)) {
23383
- try {
23384
- proxy.dispose();
23385
- }
23386
- catch { }
23616
+ disposeProxies();
23387
23617
  return;
23388
23618
  }
23389
- this.proxies.set(sub.id, proxy);
23619
+ this.proxies.set(sub.id, proxies);
23390
23620
  this.activeSubscriptions.set(sub.id, sub);
23391
23621
  // After a restart this wakes on mentions written while the waker was down; on a new
23392
- // subscription it records the existing ones as history.
23393
- if (proxy.result !== undefined) {
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;
23394
23627
  try {
23395
- await handleResult(proxy.result, true);
23628
+ await handleResult(p.result, true, of);
23396
23629
  }
23397
23630
  catch (e) {
23398
23631
  this.logger.warn(`[waker] ${sub.id}: reading the opening result failed: ${e?.message ?? e}`);
@@ -23455,16 +23688,15 @@ class WakerSubscriptionManager {
23455
23688
  dispose(id, persist = true) {
23456
23689
  // Invalidate any subscribe() for this id that is still awaiting.
23457
23690
  this.generations.set(id, (this.generations.get(id) ?? 0) + 1);
23458
- const proxy = this.proxies.get(id);
23459
- if (proxy) {
23691
+ for (const proxy of this.proxies.get(id) ?? []) {
23460
23692
  try {
23461
23693
  proxy.dispose();
23462
23694
  }
23463
23695
  catch {
23464
23696
  /* ignore */
23465
23697
  }
23466
- this.proxies.delete(id);
23467
23698
  }
23699
+ this.proxies.delete(id);
23468
23700
  const timer = this.debounceTimers.get(id);
23469
23701
  if (timer) {
23470
23702
  clearTimeout(timer);
@@ -24212,6 +24444,7 @@ exports.linkExpressionToWire = linkExpressionToWire;
24212
24444
  exports.linkMutationsToWire = linkMutationsToWire;
24213
24445
  exports.literal = literal;
24214
24446
  exports.looksLikeUri = looksLikeUri;
24447
+ exports.mentionOf = mentionOf;
24215
24448
  exports.neighbourhoodExpressionFromWire = neighbourhoodExpressionFromWire;
24216
24449
  exports.normalizeNamespaceString = normalizeNamespaceString;
24217
24450
  exports.normalizeSchemaType = normalizeSchemaType;