@coasys/ad4m 0.13.0-test-model-layer → 0.13.0-test-flows-1
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.
- package/lib/index.cjs +817 -65
- package/lib/index.js +814 -66
- package/lib/src/ai/AIClient.d.ts +13 -0
- package/lib/src/ai/AIClient.js +15 -0
- package/lib/src/ai/AITypes.d.ts +5 -0
- package/lib/src/index.js +2 -0
- package/lib/src/model/Ad4mModel.d.ts +6 -1
- package/lib/src/model/Ad4mModel.js +41 -6
- package/lib/src/model/ModelQueryBuilder.d.ts +47 -3
- package/lib/src/model/ModelQueryBuilder.js +97 -6
- package/lib/src/model/query-common.d.ts +10 -1
- package/lib/src/model/query-common.js +16 -0
- package/lib/src/model/query-sparql.d.ts +11 -0
- package/lib/src/model/query-sparql.js +93 -1
- package/lib/src/model/query-utils.js +16 -0
- package/lib/src/model/shacl-gen.js +12 -0
- package/lib/src/model/types.d.ts +320 -3
- package/lib/src/model/types.js +9 -0
- package/lib/src/perspectives/AutoProcessor.d.ts +8 -0
- package/lib/src/perspectives/FlowInstance.d.ts +176 -12
- package/lib/src/perspectives/FlowInstance.js +77 -13
- package/lib/src/perspectives/FlowModels.d.ts +40 -9
- package/lib/src/perspectives/FlowModels.js +59 -13
- package/lib/src/perspectives/PerspectiveClient.d.ts +18 -0
- package/lib/src/perspectives/PerspectiveClient.js +30 -0
- package/lib/src/perspectives/PerspectiveProxy.d.ts +69 -2
- package/lib/src/perspectives/PerspectiveProxy.js +157 -7
- package/lib/src/perspectives/WakerSubscriptionManager.d.ts +55 -5
- package/lib/src/perspectives/WakerSubscriptionManager.js +183 -8
- package/lib/src/shacl/SHACLFlow.d.ts +43 -0
- package/package.json +1 -1
- package/src/ai/AIClient.ts +16 -0
- package/src/ai/AITypes.ts +5 -0
- package/src/index.ts +2 -0
- package/src/model/Ad4mModel.test.ts +442 -0
- package/src/model/Ad4mModel.ts +39 -7
- package/src/model/ModelQueryBuilder.ts +101 -10
- package/src/model/query-common.ts +20 -1
- package/src/model/query-sparql.test.ts +115 -0
- package/src/model/query-sparql.ts +97 -1
- package/src/model/query-utils.ts +18 -0
- package/src/model/relation-filtering.test.ts +7 -0
- package/src/model/shacl-gen.ts +12 -0
- package/src/model/shacl-roundtrip.test.ts +71 -0
- package/src/model/types-typed-query.test.ts +42 -0
- package/src/model/types.ts +316 -6
- package/src/perspectives/AutoProcessor.ts +8 -0
- package/src/perspectives/FlowInstance.ts +194 -13
- package/src/perspectives/FlowModels.ts +53 -13
- package/src/perspectives/PerspectiveClient.ts +62 -0
- package/src/perspectives/PerspectiveProxy.test.ts +272 -0
- package/src/perspectives/PerspectiveProxy.ts +163 -7
- package/src/perspectives/WakerSubscriptionManager.test.ts +199 -0
- package/src/perspectives/WakerSubscriptionManager.ts +197 -9
- package/src/shacl/SHACLFlow.ts +44 -0
package/lib/index.cjs
CHANGED
|
@@ -2097,6 +2097,18 @@ interpretationHint) {
|
|
|
2097
2097
|
const propMeta = properties[propName];
|
|
2098
2098
|
if (!propMeta.through)
|
|
2099
2099
|
continue; // Skip properties without predicates
|
|
2100
|
+
// `@BelongsToOne`/`@BelongsToMany` register in both maps: the relation
|
|
2101
|
+
// registry describes the edge, and `applyPropertyMetadata` marks the
|
|
2102
|
+
// accessor read-only so the non-owning side gets no setter. Both loops
|
|
2103
|
+
// then emitted a shape for it, so an inverse relation appeared twice in
|
|
2104
|
+
// the generated SHACL — once thinly, from here, and once with its target
|
|
2105
|
+
// class, polymorphism and ordering, from the relation loop below.
|
|
2106
|
+
//
|
|
2107
|
+
// The relation loop is the complete description, so this one stands
|
|
2108
|
+
// aside. Skipping by presence in the relation map rather than by kind
|
|
2109
|
+
// keeps it right for any future decorator that registers in both.
|
|
2110
|
+
if (allRelationsMeta[propName])
|
|
2111
|
+
continue;
|
|
2100
2112
|
const propShape = {
|
|
2101
2113
|
name: propName,
|
|
2102
2114
|
path: propMeta.through,
|
|
@@ -3987,7 +3999,7 @@ var __classPrivateFieldGet$a = (undefined && undefined.__classPrivateFieldGet) |
|
|
|
3987
3999
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
3988
4000
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
3989
4001
|
};
|
|
3990
|
-
var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_reconnectUnsub, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_generation, _QuerySubscriptionProxy_deliverResult, _QuerySubscriptionProxy_startKeepalive, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, _PerspectiveProxy_ensuredSubjectClasses;
|
|
4002
|
+
var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_reconnectUnsub, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_generation, _QuerySubscriptionProxy_deliverResult, _QuerySubscriptionProxy_startKeepalive, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, _PerspectiveProxy_ensuredSubjectClasses, _PerspectiveProxy_overlaysInFlight;
|
|
3991
4003
|
/** Extract namespace prefix from a URI (everything up to and including the last / or #) */
|
|
3992
4004
|
function extractNamespaceFromUri(uri) {
|
|
3993
4005
|
const hashIdx = uri.lastIndexOf('#');
|
|
@@ -4479,6 +4491,10 @@ class PerspectiveProxy {
|
|
|
4479
4491
|
_PerspectiveProxy_perspectiveLinkUpdatedCallbacks.set(this, void 0);
|
|
4480
4492
|
_PerspectiveProxy_perspectiveSyncStateChangeCallbacks.set(this, void 0);
|
|
4481
4493
|
_PerspectiveProxy_ensuredSubjectClasses.set(this, new Set()
|
|
4494
|
+
/** The `interpretationOverlays()` RPC currently in flight, shared by concurrent callers. */
|
|
4495
|
+
);
|
|
4496
|
+
/** The `interpretationOverlays()` RPC currently in flight, shared by concurrent callers. */
|
|
4497
|
+
_PerspectiveProxy_overlaysInFlight.set(this, null
|
|
4482
4498
|
/**
|
|
4483
4499
|
* Creates a new PerspectiveProxy instance.
|
|
4484
4500
|
* Note: Don't create this directly, use ad4m.perspective.add() instead.
|
|
@@ -4693,9 +4709,28 @@ class PerspectiveProxy {
|
|
|
4693
4709
|
/**
|
|
4694
4710
|
* Pending interpretation overlays on this perspective — LLM suggestions the
|
|
4695
4711
|
* §4 divergence gate staged rather than applied, awaiting human accept/reject.
|
|
4712
|
+
*
|
|
4713
|
+
* Concurrent callers share one in-flight RPC. Nothing is kept after it
|
|
4714
|
+
* settles, so every call made after that fetches from the executor again.
|
|
4715
|
+
* {@link acceptInterpretation} and {@link rejectInterpretation} detach the
|
|
4716
|
+
* in-flight RPC, so a read issued after they resolve never joins a read
|
|
4717
|
+
* that started before the write.
|
|
4718
|
+
* Each caller gets its own copy of the array.
|
|
4696
4719
|
*/
|
|
4697
4720
|
async interpretationOverlays() {
|
|
4698
|
-
|
|
4721
|
+
if (__classPrivateFieldGet$a(this, _PerspectiveProxy_overlaysInFlight, "f")) {
|
|
4722
|
+
return [...(await __classPrivateFieldGet$a(this, _PerspectiveProxy_overlaysInFlight, "f"))];
|
|
4723
|
+
}
|
|
4724
|
+
const pending = __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").interpretationOverlays(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
|
|
4725
|
+
__classPrivateFieldSet$a(this, _PerspectiveProxy_overlaysInFlight, pending, "f");
|
|
4726
|
+
try {
|
|
4727
|
+
return [...(await pending)];
|
|
4728
|
+
}
|
|
4729
|
+
finally {
|
|
4730
|
+
if (__classPrivateFieldGet$a(this, _PerspectiveProxy_overlaysInFlight, "f") === pending) {
|
|
4731
|
+
__classPrivateFieldSet$a(this, _PerspectiveProxy_overlaysInFlight, null, "f");
|
|
4732
|
+
}
|
|
4733
|
+
}
|
|
4699
4734
|
}
|
|
4700
4735
|
/**
|
|
4701
4736
|
* Accept an interpretation overlay's suggestion(s): the LLM's staged value
|
|
@@ -4703,7 +4738,13 @@ class PerspectiveProxy {
|
|
|
4703
4738
|
* `property` to accept a single predicate; omit it for the whole base.
|
|
4704
4739
|
*/
|
|
4705
4740
|
async acceptInterpretation(base, property) {
|
|
4706
|
-
|
|
4741
|
+
try {
|
|
4742
|
+
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").acceptInterpretation(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, base, property);
|
|
4743
|
+
}
|
|
4744
|
+
finally {
|
|
4745
|
+
// A read already in flight may predate this write; later callers must not join it.
|
|
4746
|
+
__classPrivateFieldSet$a(this, _PerspectiveProxy_overlaysInFlight, null, "f");
|
|
4747
|
+
}
|
|
4707
4748
|
}
|
|
4708
4749
|
/**
|
|
4709
4750
|
* Reject an interpretation overlay's suggestion(s). Omit `property` to reject
|
|
@@ -4711,7 +4752,59 @@ class PerspectiveProxy {
|
|
|
4711
4752
|
* rejected `update` drops the overlay and keeps the real value.
|
|
4712
4753
|
*/
|
|
4713
4754
|
async rejectInterpretation(base, property) {
|
|
4714
|
-
|
|
4755
|
+
try {
|
|
4756
|
+
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").rejectInterpretation(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, base, property);
|
|
4757
|
+
}
|
|
4758
|
+
finally {
|
|
4759
|
+
// A read already in flight may predate this write; later callers must not join it.
|
|
4760
|
+
__classPrivateFieldSet$a(this, _PerspectiveProxy_overlaysInFlight, null, "f");
|
|
4761
|
+
}
|
|
4762
|
+
}
|
|
4763
|
+
/**
|
|
4764
|
+
* `outputs` names the instances a run produces, as `{ className, id }`
|
|
4765
|
+
* pairs, for a transition into a terminal state. The proposal signs a
|
|
4766
|
+
* hash over their content, and a receipt for the run can only speak for
|
|
4767
|
+
* exactly these instances, as they stood at completion. Naming outputs
|
|
4768
|
+
* for a non-terminal state is refused.
|
|
4769
|
+
*/
|
|
4770
|
+
async proposeFlowTransition(instanceUri, toState, rationale, outputs) {
|
|
4771
|
+
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").proposeFlowTransition(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, instanceUri, toState, rationale, outputs);
|
|
4772
|
+
}
|
|
4773
|
+
async acceptFlowProposal(proposalUri) {
|
|
4774
|
+
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").acceptFlowProposal(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, proposalUri);
|
|
4775
|
+
}
|
|
4776
|
+
/** Withdraw our own links from a proposal; resolves to how many went. */
|
|
4777
|
+
async rejectFlowProposal(proposalUri) {
|
|
4778
|
+
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").rejectFlowProposal(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, proposalUri);
|
|
4779
|
+
}
|
|
4780
|
+
/**
|
|
4781
|
+
* Re-decide a flow receipt under this perspective's own flow catalogue.
|
|
4782
|
+
* The verdict is three-way — see {@link FlowReceiptVerdict}: branch on
|
|
4783
|
+
* `outcome`, never on a boolean you derive from it.
|
|
4784
|
+
*/
|
|
4785
|
+
async verifyFlowReceipt(receipt) {
|
|
4786
|
+
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").verifyFlowReceipt(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, receipt);
|
|
4787
|
+
}
|
|
4788
|
+
/**
|
|
4789
|
+
* Which instances are, as they stand, valid outputs of `flow`?
|
|
4790
|
+
*
|
|
4791
|
+
* Backed by receipt verification executor-side (see
|
|
4792
|
+
* {@link FlowValidOutput}); an instance without a verifying receipt, or
|
|
4793
|
+
* edited since its run completed, is not listed. The same predicate is
|
|
4794
|
+
* available as a model-query filter:
|
|
4795
|
+
* `where: { producedByFlow: { flow, state? } }`.
|
|
4796
|
+
*
|
|
4797
|
+
* Rejects — never resolves to `[]` — when the flow is not on this
|
|
4798
|
+
* perspective, or when it carries more receipt candidates than the
|
|
4799
|
+
* executor's per-flow budget (256): "could not read every receipt" is not
|
|
4800
|
+
* "no valid outputs". The filter rejects the same way.
|
|
4801
|
+
*/
|
|
4802
|
+
async flowValidOutputs(flow, state) {
|
|
4803
|
+
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").flowValidOutputs(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, flow, state);
|
|
4804
|
+
}
|
|
4805
|
+
/** Mint and store the receipt for a completed flow run. */
|
|
4806
|
+
async mintFlowReceipt(instanceUri) {
|
|
4807
|
+
return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").mintFlowReceipt(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, instanceUri);
|
|
4715
4808
|
}
|
|
4716
4809
|
/** Subscribe to this perspective's auto-processor step signals. */
|
|
4717
4810
|
async addAutoProcessorEventListener(cb) {
|
|
@@ -4957,11 +5050,48 @@ class PerspectiveProxy {
|
|
|
4957
5050
|
/**
|
|
4958
5051
|
* Removes a link from the perspective.
|
|
4959
5052
|
*
|
|
4960
|
-
*
|
|
5053
|
+
* Accepts either a full `LinkExpressionInput` (as returned by `add`) or a bare
|
|
5054
|
+
* `Link` (source/predicate/target only). When a bare Link is passed the method
|
|
5055
|
+
* resolves it to the first stored `LinkExpression` whose source, predicate, and
|
|
5056
|
+
* target match, then removes that expression. A bare Link without a predicate
|
|
5057
|
+
* (or with the constructor's `""` stand-in) matches only stored links that
|
|
5058
|
+
* themselves have no predicate. If no match is found an error is thrown
|
|
5059
|
+
* naming the link so the caller knows what was expected.
|
|
5060
|
+
*
|
|
5061
|
+
* @param link - The link to remove (LinkExpressionInput or bare Link)
|
|
4961
5062
|
* @param batchId - Optional batch ID to group this operation with others
|
|
4962
5063
|
*/
|
|
4963
5064
|
async remove(link, batchId) {
|
|
4964
|
-
|
|
5065
|
+
let resolvedLink;
|
|
5066
|
+
if (!('data' in link) || link.data === undefined) {
|
|
5067
|
+
// bare Link — resolve to stored expression
|
|
5068
|
+
const bare = link;
|
|
5069
|
+
// The Link constructor coerces an absent predicate to "" and the
|
|
5070
|
+
// store reports predicate-less links as predicate null — so ""
|
|
5071
|
+
// and undefined both mean "no predicate" here, and neither may
|
|
5072
|
+
// widen the query: dropping the filter would resolve (and
|
|
5073
|
+
// remove!) an arbitrary source→target link under a *different*
|
|
5074
|
+
// predicate. LinkQuery cannot express "predicate is absent", so
|
|
5075
|
+
// in that case we query on source/target only and require the
|
|
5076
|
+
// absence ourselves.
|
|
5077
|
+
const predicateGiven = bare.predicate !== undefined && bare.predicate !== '';
|
|
5078
|
+
const candidates = await this.get(new LinkQuery({
|
|
5079
|
+
source: bare.source || undefined,
|
|
5080
|
+
predicate: predicateGiven ? bare.predicate : undefined,
|
|
5081
|
+
target: bare.target || undefined,
|
|
5082
|
+
}));
|
|
5083
|
+
const matches = predicateGiven
|
|
5084
|
+
? candidates
|
|
5085
|
+
: candidates.filter(m => !m.data.predicate);
|
|
5086
|
+
if (matches.length === 0) {
|
|
5087
|
+
throw new Error(`PerspectiveProxy.remove: no stored LinkExpression matches Link { source: "${bare.source}", predicate: "${bare.predicate}", target: "${bare.target}" }`);
|
|
5088
|
+
}
|
|
5089
|
+
resolvedLink = matches[0];
|
|
5090
|
+
}
|
|
5091
|
+
else {
|
|
5092
|
+
resolvedLink = link;
|
|
5093
|
+
}
|
|
5094
|
+
const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, resolvedLink, batchId);
|
|
4965
5095
|
invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
|
|
4966
5096
|
return result;
|
|
4967
5097
|
}
|
|
@@ -5549,6 +5679,38 @@ class PerspectiveProxy {
|
|
|
5549
5679
|
return [];
|
|
5550
5680
|
}
|
|
5551
5681
|
}
|
|
5682
|
+
/**
|
|
5683
|
+
* Return the full target-class URIs of every registered SubjectClass.
|
|
5684
|
+
*
|
|
5685
|
+
* Unlike {@link subjectClasses}, which strips the namespace and returns bare
|
|
5686
|
+
* names (`"Space"`, `"Channel"`), this method returns the complete URIs
|
|
5687
|
+
* (`"we://Space"`, `"flux://Channel"`). The full URI is the key that
|
|
5688
|
+
* `load_shape` resolves against, so it is the only collision-safe identifier
|
|
5689
|
+
* — two apps can both declare a class called `"Template"` under different
|
|
5690
|
+
* namespaces, and the bare name cannot distinguish them.
|
|
5691
|
+
*
|
|
5692
|
+
* Callers that need to check whether a *set* of models are already
|
|
5693
|
+
* registered should call this once and test membership against the returned
|
|
5694
|
+
* set, rather than issuing one `queryLinks` per model.
|
|
5695
|
+
*
|
|
5696
|
+
* One `queryLinks` round trip, no executor-side changes.
|
|
5697
|
+
*/
|
|
5698
|
+
async subjectClassTargetClasses() {
|
|
5699
|
+
try {
|
|
5700
|
+
const classLinks = await this.get(new LinkQuery({
|
|
5701
|
+
predicate: "rdf://type",
|
|
5702
|
+
target: "ad4m://SubjectClass"
|
|
5703
|
+
}));
|
|
5704
|
+
const uris = classLinks
|
|
5705
|
+
.map(l => l.data.source)
|
|
5706
|
+
.filter(source => source.length > 0);
|
|
5707
|
+
return [...new Set(uris)];
|
|
5708
|
+
}
|
|
5709
|
+
catch (e) {
|
|
5710
|
+
console.warn('subjectClassTargetClasses: lookup failed:', e);
|
|
5711
|
+
return [];
|
|
5712
|
+
}
|
|
5713
|
+
}
|
|
5552
5714
|
async stringOrTemplateObjectToSubjectClassName(subjectClass) {
|
|
5553
5715
|
if (typeof subjectClass === "string")
|
|
5554
5716
|
return subjectClass;
|
|
@@ -6271,7 +6433,7 @@ class PerspectiveProxy {
|
|
|
6271
6433
|
return subscriptionProxy;
|
|
6272
6434
|
}
|
|
6273
6435
|
}
|
|
6274
|
-
_PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveProxy_ensuredSubjectClasses = new WeakMap();
|
|
6436
|
+
_PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveProxy_ensuredSubjectClasses = new WeakMap(), _PerspectiveProxy_overlaysInFlight = new WeakMap();
|
|
6275
6437
|
|
|
6276
6438
|
var __classPrivateFieldSet$9 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
6277
6439
|
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
@@ -6563,6 +6725,36 @@ class PerspectiveClient {
|
|
|
6563
6725
|
async rejectInterpretation(uuid, base, property) {
|
|
6564
6726
|
return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectInterpretation', { uuid, base, property });
|
|
6565
6727
|
}
|
|
6728
|
+
async proposeFlowTransition(uuid, instanceUri, toState, rationale, outputs) {
|
|
6729
|
+
return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.proposeFlowTransition', { uuid, instanceUri, toState, rationale, outputs });
|
|
6730
|
+
}
|
|
6731
|
+
async acceptFlowProposal(uuid, proposalUri) {
|
|
6732
|
+
return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.acceptFlowProposal', { uuid, proposalUri });
|
|
6733
|
+
}
|
|
6734
|
+
/**
|
|
6735
|
+
* Withdraw this agent's own links from a proposal. Resolves to how many
|
|
6736
|
+
* were retracted — one for a withdrawn vote, more when retracting a
|
|
6737
|
+
* proposal this agent opened.
|
|
6738
|
+
*/
|
|
6739
|
+
async rejectFlowProposal(uuid, proposalUri) {
|
|
6740
|
+
const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectFlowProposal', { uuid, proposalUri });
|
|
6741
|
+
return result.retractedLinks;
|
|
6742
|
+
}
|
|
6743
|
+
/** Re-decide a flow receipt under this perspective's own flow catalogue. */
|
|
6744
|
+
async verifyFlowReceipt(uuid, receipt) {
|
|
6745
|
+
return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.verifyFlowReceipt', { uuid, receipt });
|
|
6746
|
+
}
|
|
6747
|
+
/** The instances that are, as they stand, valid outputs of `flow`
|
|
6748
|
+
* (optionally: of runs settled into terminal state `state`). */
|
|
6749
|
+
async flowValidOutputs(uuid, flow, state) {
|
|
6750
|
+
return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.flowValidOutputs', { uuid, flow, state });
|
|
6751
|
+
}
|
|
6752
|
+
/** Mint and store the receipt for a completed flow run. Fails while the
|
|
6753
|
+
* run has not settled into a terminal state, and when an output's
|
|
6754
|
+
* content no longer matches what the quorum committed to. */
|
|
6755
|
+
async mintFlowReceipt(uuid, instanceUri) {
|
|
6756
|
+
return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.mintFlowReceipt', { uuid, instanceUri });
|
|
6757
|
+
}
|
|
6566
6758
|
/**
|
|
6567
6759
|
* Subscribe to auto-processor step signals. `cb` fires for every
|
|
6568
6760
|
* `auto-processor-event` on `uuid` (BatchReady → Claimed/BackedOff/… →
|
|
@@ -14927,6 +15119,21 @@ class AIClient {
|
|
|
14927
15119
|
async getModels() {
|
|
14928
15120
|
return __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.models');
|
|
14929
15121
|
}
|
|
15122
|
+
/**
|
|
15123
|
+
* Ask a remote endpoint which models it serves, before adding one.
|
|
15124
|
+
*
|
|
15125
|
+
* Takes the credentials of a model that does not exist yet — a settings
|
|
15126
|
+
* form is being filled in and wants the list to pick from. Rejects when
|
|
15127
|
+
* the endpoint is unreachable or the key is refused, which makes this the
|
|
15128
|
+
* credential check too: without it a bad key surfaces later as a failed
|
|
15129
|
+
* completion carrying an error from a different layer.
|
|
15130
|
+
*
|
|
15131
|
+
* `apiType` defaults to the OpenAI shape, which is what every endpoint
|
|
15132
|
+
* that is not Anthropic speaks.
|
|
15133
|
+
*/
|
|
15134
|
+
async discoverModels(baseUrl, apiKey, apiType) {
|
|
15135
|
+
return __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.discoverModels', { baseUrl, apiKey, apiType });
|
|
15136
|
+
}
|
|
14930
15137
|
async addModel(model) {
|
|
14931
15138
|
return __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.addModel', { model: this.serializeModelInput(model) });
|
|
14932
15139
|
}
|
|
@@ -15037,6 +15244,27 @@ class AIClient {
|
|
|
15037
15244
|
}
|
|
15038
15245
|
_AIClient_apiClient = new WeakMap(), _AIClient_transcriptionUnsubscribers = new WeakMap(), _AIClient_pendingStreamIds = new WeakMap();
|
|
15039
15246
|
|
|
15247
|
+
/**
|
|
15248
|
+
* Shared type definitions for the Ad4mModel system.
|
|
15249
|
+
*
|
|
15250
|
+
* Extracted into a standalone module so that utility files
|
|
15251
|
+
* (`query-utils.ts`, `decorators.ts`, etc.) can import types without
|
|
15252
|
+
* creating circular runtime dependencies on `Ad4mModel.ts`.
|
|
15253
|
+
*/
|
|
15254
|
+
/**
|
|
15255
|
+
* Whether this scope is a traversal rather than a single named parent.
|
|
15256
|
+
*
|
|
15257
|
+
* The other two forms carry `id`; this one carries `ids` and may name several,
|
|
15258
|
+
* so anything reaching for one parent — every write path — has to ask first.
|
|
15259
|
+
*/
|
|
15260
|
+
function isTraverseScope(scope) {
|
|
15261
|
+
return 'ids' in scope;
|
|
15262
|
+
}
|
|
15263
|
+
/** Type guard for IncludeProjection objects. */
|
|
15264
|
+
function isIncludeProjection(val) {
|
|
15265
|
+
return typeof val === 'object' && val !== null && 'from' in val;
|
|
15266
|
+
}
|
|
15267
|
+
|
|
15040
15268
|
/**
|
|
15041
15269
|
* Shared query helpers used by both the Prolog and SPARQL query pipelines.
|
|
15042
15270
|
*/
|
|
@@ -15049,6 +15277,21 @@ _AIClient_apiClient = new WeakMap(), _AIClient_transcriptionUnsubscribers = new
|
|
|
15049
15277
|
* - With `field`: direct key lookup
|
|
15050
15278
|
* - Without `field`: scan for a relation whose `target()` matches `childCtor`
|
|
15051
15279
|
*/
|
|
15280
|
+
/**
|
|
15281
|
+
* Narrow a scope to the one-parent forms, for the paths that write a link.
|
|
15282
|
+
*
|
|
15283
|
+
* A traversal describes a read outward from several anchors. Creating a record
|
|
15284
|
+
* "under" one would have to pick which, and nothing in the scope says — so this
|
|
15285
|
+
* refuses rather than guessing at the first of the list. The executor's write
|
|
15286
|
+
* scopes refuse it for the same reason.
|
|
15287
|
+
*/
|
|
15288
|
+
function requireSingleParent(parent) {
|
|
15289
|
+
if (isTraverseScope(parent)) {
|
|
15290
|
+
throw new Error('parent(): a traverse scope describes a read and names no single parent to write under. ' +
|
|
15291
|
+
'Use { id, predicate } or { model, id } when creating a record under a parent.');
|
|
15292
|
+
}
|
|
15293
|
+
return parent;
|
|
15294
|
+
}
|
|
15052
15295
|
function resolveParentPredicate(parent, childCtor) {
|
|
15053
15296
|
// Raw form — explicit predicate
|
|
15054
15297
|
if ('predicate' in parent)
|
|
@@ -15453,6 +15696,68 @@ function hasJsOnlyWhereFilters(metadata, allRelationsMetadata, where) {
|
|
|
15453
15696
|
}
|
|
15454
15697
|
return false;
|
|
15455
15698
|
}
|
|
15699
|
+
/**
|
|
15700
|
+
* Prepare a `where` for this client-side SPARQL builder: unwrap `{ eq: X }`
|
|
15701
|
+
* to the bare `X`, and refuse a per-link `author`.
|
|
15702
|
+
*
|
|
15703
|
+
* A per-link `author` (nested, `{ agent: { eq: X, author: A } }`, or a
|
|
15704
|
+
* top-level `author` beside link-backed property or relation conditions) is
|
|
15705
|
+
* answered by the executor, which joins each matched link's reifier (#1114). This builder
|
|
15706
|
+
* has no such join, and treating the author as instance-level here would
|
|
15707
|
+
* answer a different, wider question. `findAll()`/`count()` answer it.
|
|
15708
|
+
*/
|
|
15709
|
+
function normalizeWhereForSparql(metadata, where) {
|
|
15710
|
+
if (!where)
|
|
15711
|
+
return where;
|
|
15712
|
+
assertNoPerLinkAuthor(metadata, where);
|
|
15713
|
+
const out = {};
|
|
15714
|
+
for (const [key, condition] of Object.entries(where)) {
|
|
15715
|
+
out[key] = unwrapEq(key, condition);
|
|
15716
|
+
}
|
|
15717
|
+
return out;
|
|
15718
|
+
}
|
|
15719
|
+
function isOpsObject(condition) {
|
|
15720
|
+
return typeof condition === "object" && condition !== null && !Array.isArray(condition);
|
|
15721
|
+
}
|
|
15722
|
+
function unwrapEq(key, condition) {
|
|
15723
|
+
if (key === "OR" || key === "AND" || key === "NOT" || !isOpsObject(condition) || condition.eq === undefined) {
|
|
15724
|
+
return condition;
|
|
15725
|
+
}
|
|
15726
|
+
if (Object.keys(condition).some((k) => k !== "eq")) {
|
|
15727
|
+
throw new Error(`where.${key}: \`eq\` cannot be combined with another operator`);
|
|
15728
|
+
}
|
|
15729
|
+
return condition.eq;
|
|
15730
|
+
}
|
|
15731
|
+
function assertNoPerLinkAuthor(metadata, where) {
|
|
15732
|
+
const refuse = (what) => {
|
|
15733
|
+
throw new Error(`buildSPARQLQuery: ${what} is a per-link \`author\`, which the executor answers by ` +
|
|
15734
|
+
"checking who wrote each matched link. This client-side SPARQL builder cannot express " +
|
|
15735
|
+
"it. Use the model query path (findAll/count).");
|
|
15736
|
+
};
|
|
15737
|
+
// A property or a relation with a predicate, as the executor's `is_link_leaf`.
|
|
15738
|
+
const linkBacked = (key) => {
|
|
15739
|
+
const field = metadata.properties[key] ?? metadata.relations?.[key];
|
|
15740
|
+
return !!field && !!field.predicate && !field.getter;
|
|
15741
|
+
};
|
|
15742
|
+
for (const [key, condition] of Object.entries(where)) {
|
|
15743
|
+
if (key === "OR" || key === "AND") {
|
|
15744
|
+
for (const branch of condition ?? [])
|
|
15745
|
+
assertNoPerLinkAuthor(metadata, branch);
|
|
15746
|
+
}
|
|
15747
|
+
else if (key === "NOT") {
|
|
15748
|
+
if (condition)
|
|
15749
|
+
assertNoPerLinkAuthor(metadata, condition);
|
|
15750
|
+
}
|
|
15751
|
+
else if (key === "author") {
|
|
15752
|
+
const sibling = Object.keys(where).find((k) => k !== "author" && linkBacked(k));
|
|
15753
|
+
if (sibling)
|
|
15754
|
+
refuse(`\`author\` beside \`${sibling}\``);
|
|
15755
|
+
}
|
|
15756
|
+
else if (isOpsObject(condition) && condition.author !== undefined) {
|
|
15757
|
+
refuse(`\`${key}.author\``);
|
|
15758
|
+
}
|
|
15759
|
+
}
|
|
15760
|
+
}
|
|
15456
15761
|
/**
|
|
15457
15762
|
* Check whether a string value is a well-formed absolute IRI that can be
|
|
15458
15763
|
* stored verbatim as a link target (raw `NamedNode`) instead of being
|
|
@@ -15626,11 +15931,40 @@ function mapPropertyToSPARQLVar(propertyName, metadata) {
|
|
|
15626
15931
|
function buildSPARQLQuery(metadata, allRelationsMetadata, query, modelClass) {
|
|
15627
15932
|
const joinPatterns = [];
|
|
15628
15933
|
const filterExpressions = [];
|
|
15934
|
+
query = { ...query, where: normalizeWhereForSparql(metadata, query.where) };
|
|
15629
15935
|
// Parent filter — direct triple pattern
|
|
15630
15936
|
if (query.parent) {
|
|
15631
15937
|
const parentPredicate = resolveParentPredicate(query.parent, modelClass);
|
|
15632
|
-
|
|
15938
|
+
if (isTraverseScope(query.parent)) {
|
|
15939
|
+
const { ids, transitive, direction, limitPerAnchor, levels } = query.parent;
|
|
15940
|
+
// `limitPerAnchor` and `levels` are applied by the executor between
|
|
15941
|
+
// selecting ids and hydrating them, which is a shape this path does not
|
|
15942
|
+
// have — it builds one query and reads the rows. Refused rather than
|
|
15943
|
+
// ignored: quietly returning every reply where five per parent were
|
|
15944
|
+
// asked for — or one unbounded level where a walk was asked for — is a
|
|
15945
|
+
// wrong answer that looks like a right one.
|
|
15946
|
+
if (limitPerAnchor !== undefined) {
|
|
15947
|
+
throw new Error('buildSPARQLQuery: limitPerAnchor is applied by the executor between query phases and ' +
|
|
15948
|
+
'has no equivalent here. Use the model query path for per-anchor limits.');
|
|
15949
|
+
}
|
|
15950
|
+
if (levels !== undefined) {
|
|
15951
|
+
throw new Error('buildSPARQLQuery: levels is walked by the executor between query phases and ' +
|
|
15952
|
+
'has no equivalent here. Use the model query path for level walks.');
|
|
15953
|
+
}
|
|
15954
|
+
const anchors = (Array.isArray(ids) ? ids : [ids]).map(iri).join(' ');
|
|
15955
|
+
const path = transitive ? '+' : '';
|
|
15956
|
+
joinPatterns.push(`
|
|
15957
|
+
VALUES ?_anchor { ${anchors} }`);
|
|
15958
|
+
joinPatterns.push(direction === 'in'
|
|
15959
|
+
? `
|
|
15960
|
+
?source ${iri(parentPredicate)}${path} ?_anchor .`
|
|
15961
|
+
: `
|
|
15962
|
+
?_anchor ${iri(parentPredicate)}${path} ?source .`);
|
|
15963
|
+
}
|
|
15964
|
+
else {
|
|
15965
|
+
joinPatterns.push(`
|
|
15633
15966
|
${iri(query.parent.id)} ${iri(parentPredicate)} ?source .`);
|
|
15967
|
+
}
|
|
15634
15968
|
}
|
|
15635
15969
|
// Required property JOIN patterns — direct triple patterns
|
|
15636
15970
|
let hasConformance = false;
|
|
@@ -16127,6 +16461,23 @@ class ModelQueryBuilder {
|
|
|
16127
16461
|
this.queryParams.properties = properties;
|
|
16128
16462
|
return this;
|
|
16129
16463
|
}
|
|
16464
|
+
/**
|
|
16465
|
+
* Asks for the individual links behind each instance — author, timestamp
|
|
16466
|
+
* and proof per link — under `instance.__links`. See `Query.links`.
|
|
16467
|
+
*
|
|
16468
|
+
* @param keys - Property / relation names, or absolute predicate IRIs
|
|
16469
|
+
* @returns The query builder for chaining
|
|
16470
|
+
*
|
|
16471
|
+
* @example
|
|
16472
|
+
* ```typescript
|
|
16473
|
+
* const [post] = await Post.query(perspective).links(["comments"]).get();
|
|
16474
|
+
* post.__links!.comments.map((l) => l.timestamp); // when each comment was attached
|
|
16475
|
+
* ```
|
|
16476
|
+
*/
|
|
16477
|
+
links(keys) {
|
|
16478
|
+
this.queryParams.links = keys;
|
|
16479
|
+
return this;
|
|
16480
|
+
}
|
|
16130
16481
|
/**
|
|
16131
16482
|
* Controls whether SPARQL property getters are evaluated during hydration.
|
|
16132
16483
|
*
|
|
@@ -16149,6 +16500,42 @@ class ModelQueryBuilder {
|
|
|
16149
16500
|
this.queryParams.deepQuery = enabled;
|
|
16150
16501
|
return this;
|
|
16151
16502
|
}
|
|
16503
|
+
/**
|
|
16504
|
+
* Reads instances as they exist in links of one status only.
|
|
16505
|
+
*
|
|
16506
|
+
* `'shared'` leaves out every Local link, both from the values returned and
|
|
16507
|
+
* from what decides which instances are returned. Use it when the data is
|
|
16508
|
+
* shown to another user. `'local'` is the converse: it returns only
|
|
16509
|
+
* instances flagged in a Local link, so a Local note on a card flagged only
|
|
16510
|
+
* in a Shared link is read without `linkStatus`, not under `'local'`.
|
|
16511
|
+
* See {@link Query.linkStatus}.
|
|
16512
|
+
*
|
|
16513
|
+
* @param status - `'shared'` or `'local'`
|
|
16514
|
+
* @returns The query builder for chaining
|
|
16515
|
+
*
|
|
16516
|
+
* @example
|
|
16517
|
+
* ```typescript
|
|
16518
|
+
* const cards = await Card.query(perspective).linkStatus('shared').get();
|
|
16519
|
+
* ```
|
|
16520
|
+
*/
|
|
16521
|
+
linkStatus(status) {
|
|
16522
|
+
this.queryParams.linkStatus = status;
|
|
16523
|
+
return this;
|
|
16524
|
+
}
|
|
16525
|
+
/**
|
|
16526
|
+
* Also hydrate from links whose signature did not verify.
|
|
16527
|
+
*
|
|
16528
|
+
* Off by default: the executor withholds unverified links. Turn it on only
|
|
16529
|
+
* to *display* an unverified claim, never for data you act on. See
|
|
16530
|
+
* {@link Query.includeUnverified}.
|
|
16531
|
+
*
|
|
16532
|
+
* @param enabled - Whether to include unverified links (default: true)
|
|
16533
|
+
* @returns The query builder for chaining
|
|
16534
|
+
*/
|
|
16535
|
+
includeUnverified(enabled = true) {
|
|
16536
|
+
this.queryParams.includeUnverified = enabled;
|
|
16537
|
+
return this;
|
|
16538
|
+
}
|
|
16152
16539
|
/**
|
|
16153
16540
|
* Specifies which relations to eager-load (hydrate into model instances).
|
|
16154
16541
|
*
|
|
@@ -16289,13 +16676,10 @@ class ModelQueryBuilder {
|
|
|
16289
16676
|
const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
|
|
16290
16677
|
try {
|
|
16291
16678
|
const results = parseResults(rawResult);
|
|
16292
|
-
console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${results.length} instances`);
|
|
16293
16679
|
const fp = buildFingerprint(results);
|
|
16294
16680
|
if (fp === lastResultFingerprint) {
|
|
16295
|
-
console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
|
|
16296
16681
|
return;
|
|
16297
16682
|
}
|
|
16298
|
-
console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
|
|
16299
16683
|
lastResultFingerprint = fp;
|
|
16300
16684
|
callback(results);
|
|
16301
16685
|
}
|
|
@@ -16564,15 +16948,56 @@ class ModelQueryBuilder {
|
|
|
16564
16948
|
offset: pageSize * (pageNumber - 1),
|
|
16565
16949
|
count: true,
|
|
16566
16950
|
};
|
|
16951
|
+
// One read in flight. A dispatch while a read is running sets `pending`
|
|
16952
|
+
// so a fetch always completes after the last dispatch. The generation
|
|
16953
|
+
// counter from #1020 dropped superseded fetches, but ordered them by
|
|
16954
|
+
// start time rather than by how fresh the data they read was — two
|
|
16955
|
+
// back-to-back dispatches could keep the fetch that saw 1 model and
|
|
16956
|
+
// drop the one that saw 2, after which the server has nothing further
|
|
16957
|
+
// to say (issue #1051 / CI: "Paginate callback did not see second model save").
|
|
16958
|
+
// After dispose() no read starts and no result is delivered, including
|
|
16959
|
+
// a read that was already in flight when dispose() ran.
|
|
16960
|
+
let disposed = false;
|
|
16961
|
+
let fetching = false;
|
|
16962
|
+
let pending = false;
|
|
16963
|
+
let coalesced = 0;
|
|
16567
16964
|
const processResults = async () => {
|
|
16568
|
-
|
|
16569
|
-
|
|
16965
|
+
if (disposed)
|
|
16966
|
+
return;
|
|
16967
|
+
if (fetching) {
|
|
16968
|
+
pending = true;
|
|
16969
|
+
coalesced++;
|
|
16970
|
+
return;
|
|
16971
|
+
}
|
|
16972
|
+
fetching = true;
|
|
16973
|
+
try {
|
|
16974
|
+
const { results, totalCount } = await ctor.executeModelQuery(this.perspective, paginatedQuery, this.modelClassName);
|
|
16975
|
+
if (!disposed)
|
|
16976
|
+
callback({ results, totalCount, pageSize, pageNumber });
|
|
16977
|
+
}
|
|
16978
|
+
finally {
|
|
16979
|
+
fetching = false;
|
|
16980
|
+
if (pending) {
|
|
16981
|
+
const dispatches = coalesced;
|
|
16982
|
+
pending = false;
|
|
16983
|
+
coalesced = 0;
|
|
16984
|
+
// Whether a trailing fetch actually starts is decided by the entry
|
|
16985
|
+
// guard at the top of processResults, which returns when disposed.
|
|
16986
|
+
// Log only what that guard will let through, or the dispose path
|
|
16987
|
+
// announces a fetch it then drops.
|
|
16988
|
+
if (!disposed) {
|
|
16989
|
+
console.debug(`[ModelQueryBuilder.paginateSubscribe] ${dispatches} dispatch(es) during read for ${subscriptionId}, coalesced into one trailing fetch`);
|
|
16990
|
+
}
|
|
16991
|
+
// Detached from the caller's promise: needs its own handler, or a
|
|
16992
|
+
// rejection here is unhandled.
|
|
16993
|
+
processResults().catch(e => console.error('Paginate subscription error:', e));
|
|
16994
|
+
}
|
|
16995
|
+
}
|
|
16570
16996
|
};
|
|
16571
16997
|
const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
|
|
16572
16998
|
console.debug(`[ModelQueryBuilder.paginateSubscribe] Update received for ${subscriptionId}, re-fetching paginated data...`);
|
|
16573
16999
|
processResults().catch(e => console.error('Paginate subscription error:', e));
|
|
16574
17000
|
});
|
|
16575
|
-
let disposed = false;
|
|
16576
17001
|
let keepaliveTimer;
|
|
16577
17002
|
let resubscribeAttempts = 0;
|
|
16578
17003
|
const MAX_RESUBSCRIBE_ATTEMPTS = 5;
|
|
@@ -17540,7 +17965,33 @@ class Ad4mModel {
|
|
|
17540
17965
|
const queryInput = {};
|
|
17541
17966
|
if (query.parent) {
|
|
17542
17967
|
const parentPredicate = resolveParentPredicate(query.parent, this);
|
|
17543
|
-
|
|
17968
|
+
// A traversal keeps its own shape on the wire: the executor reads `ids`,
|
|
17969
|
+
// and flattening it to one `id` here is how a request for a whole level
|
|
17970
|
+
// would quietly become a request for one parent's children.
|
|
17971
|
+
//
|
|
17972
|
+
// Its fields are named rather than spread, because `model` — the class
|
|
17973
|
+
// itself — is how the scope may name its predicate, and that is a
|
|
17974
|
+
// constructor, not something to put in a query variable. The predicate is
|
|
17975
|
+
// resolved above; what travels is the result.
|
|
17976
|
+
if (isTraverseScope(query.parent)) {
|
|
17977
|
+
const t = query.parent;
|
|
17978
|
+
const traverse = {
|
|
17979
|
+
ids: t.ids,
|
|
17980
|
+
predicate: parentPredicate,
|
|
17981
|
+
};
|
|
17982
|
+
if (t.transitive !== undefined)
|
|
17983
|
+
traverse.transitive = t.transitive;
|
|
17984
|
+
if (t.direction !== undefined)
|
|
17985
|
+
traverse.direction = t.direction;
|
|
17986
|
+
if (t.limitPerAnchor !== undefined)
|
|
17987
|
+
traverse.limitPerAnchor = t.limitPerAnchor;
|
|
17988
|
+
if (t.levels !== undefined)
|
|
17989
|
+
traverse.levels = t.levels;
|
|
17990
|
+
queryInput.parent = traverse;
|
|
17991
|
+
}
|
|
17992
|
+
else {
|
|
17993
|
+
queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
|
|
17994
|
+
}
|
|
17544
17995
|
}
|
|
17545
17996
|
if (query.properties)
|
|
17546
17997
|
queryInput.properties = query.properties;
|
|
@@ -17602,7 +18053,13 @@ class Ad4mModel {
|
|
|
17602
18053
|
queryInput.limit = query.limit;
|
|
17603
18054
|
if (query.count !== undefined)
|
|
17604
18055
|
queryInput.count = query.count;
|
|
18056
|
+
if (query.links)
|
|
18057
|
+
queryInput.links = query.links;
|
|
17605
18058
|
queryInput.deepQuery = query.deepQuery ?? true;
|
|
18059
|
+
if (query.linkStatus != null)
|
|
18060
|
+
queryInput.linkStatus = query.linkStatus;
|
|
18061
|
+
if (query.includeUnverified !== undefined)
|
|
18062
|
+
queryInput.includeUnverified = query.includeUnverified;
|
|
17606
18063
|
// Conformance getters, where filters, and target shapes for includes
|
|
17607
18064
|
// are all resolved by the executor from the perspective's SHACL triples
|
|
17608
18065
|
// — no client-side pre-computation is needed any more.
|
|
@@ -18312,9 +18769,10 @@ class Ad4mModel {
|
|
|
18312
18769
|
if (options?.parent && !options?.batchId) {
|
|
18313
18770
|
const batchId = await perspective.createBatch();
|
|
18314
18771
|
await instance.save(batchId);
|
|
18315
|
-
const
|
|
18772
|
+
const parent = requireSingleParent(options.parent);
|
|
18773
|
+
const predicate = resolveParentPredicate(parent, this);
|
|
18316
18774
|
const link = new Link({
|
|
18317
|
-
source:
|
|
18775
|
+
source: parent.id,
|
|
18318
18776
|
predicate,
|
|
18319
18777
|
target: instance.id,
|
|
18320
18778
|
});
|
|
@@ -18328,9 +18786,10 @@ class Ad4mModel {
|
|
|
18328
18786
|
await instance.save(options?.batchId);
|
|
18329
18787
|
// Create parent → child link if a parent scope was provided
|
|
18330
18788
|
if (options?.parent) {
|
|
18331
|
-
const
|
|
18789
|
+
const parent = requireSingleParent(options.parent);
|
|
18790
|
+
const predicate = resolveParentPredicate(parent, this);
|
|
18332
18791
|
const link = new Link({
|
|
18333
|
-
source:
|
|
18792
|
+
source: parent.id,
|
|
18334
18793
|
predicate,
|
|
18335
18794
|
target: instance.id,
|
|
18336
18795
|
});
|
|
@@ -19127,14 +19586,14 @@ exports.InterpretationOverlay = __decorate$1([
|
|
|
19127
19586
|
* Querying:
|
|
19128
19587
|
* const pending = await FlowTransitionProposal.findAll(perspective);
|
|
19129
19588
|
*
|
|
19130
|
-
* Slice 5/7 of the flow-implementation arc (design doc §4.2). The Rust
|
|
19131
|
-
*
|
|
19132
|
-
*
|
|
19133
|
-
*
|
|
19134
|
-
*
|
|
19135
|
-
*
|
|
19136
|
-
* - the
|
|
19137
|
-
*
|
|
19589
|
+
* Slice 5/7 of the flow-implementation arc (design doc §4.2). The Rust engine
|
|
19590
|
+
* mints these as of #987 — see `flow_classes.rs` (`mint_proposal`, URIs at
|
|
19591
|
+
* `ad4m://flow/proposal/{id}`) — and reads them back in
|
|
19592
|
+
* `flow_instance/atom.rs`. A UI mints or joins them through
|
|
19593
|
+
* `FlowInstance.proposeTransition`. This class is the client-side mirror:
|
|
19594
|
+
* - clients build UI over proposals without knowing the raw link predicates;
|
|
19595
|
+
* - the SDNA-parity test locks TS/Rust drift against
|
|
19596
|
+
* `rust-executor/src/perspectives/hardwired_sdna/flow_transition_proposal.json`.
|
|
19138
19597
|
*/
|
|
19139
19598
|
var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
|
|
19140
19599
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
@@ -19148,9 +19607,12 @@ var __metadata = (undefined && undefined.__metadata) || function (k, v) {
|
|
|
19148
19607
|
// ── FlowTransitionProposal ──────────────────────────────────────────────────
|
|
19149
19608
|
// Mirrors the Rust hardwired `flow_transition_proposal.json` SDNA (once wired
|
|
19150
19609
|
// on the engine side; see file header). One node per proposed transition; the
|
|
19151
|
-
// URI is `ad4m://flow/proposal/<
|
|
19152
|
-
//
|
|
19153
|
-
//
|
|
19610
|
+
// URI the engine mints is `ad4m://flow/proposal/<hash>` — the content address
|
|
19611
|
+
// of the proposer-signed fields under the `nonce` (#1108). The class carries
|
|
19612
|
+
// no URI-format constraint, but a proposal whose URI is not that content
|
|
19613
|
+
// address (including any app-chosen URI) is not engine-visible: co-signatures
|
|
19614
|
+
// name the URI, so the engine only counts proposals whose URI commits to
|
|
19615
|
+
// their fields.
|
|
19154
19616
|
exports.FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel {
|
|
19155
19617
|
constructor() {
|
|
19156
19618
|
super(...arguments);
|
|
@@ -19183,6 +19645,31 @@ exports.FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel
|
|
|
19183
19645
|
* no rich-object type; the engine parses it back into a map.
|
|
19184
19646
|
*/
|
|
19185
19647
|
this.evidenceHashes = "";
|
|
19648
|
+
/**
|
|
19649
|
+
* The instances the proposer names as the run's outputs. Written only on
|
|
19650
|
+
* a proposal into a terminal state; one link per output, ordering not
|
|
19651
|
+
* significant. Each entry is the canonical JSON text of a
|
|
19652
|
+
* `{ className, id }` pair (`FlowOutputRef`); `JSON.parse` it to read one.
|
|
19653
|
+
*/
|
|
19654
|
+
this.outputs = [];
|
|
19655
|
+
/**
|
|
19656
|
+
* SHA-256 (hex) over the named outputs' content (each instance as
|
|
19657
|
+
* `model_query` returns it through its class), signed by the proposer
|
|
19658
|
+
* next to the evidence seal. Co-signers load the outputs and recompute it
|
|
19659
|
+
* before voting, and a flow receipt's output preimages must hash to it.
|
|
19660
|
+
* Empty on a proposal into a non-terminal state.
|
|
19661
|
+
*/
|
|
19662
|
+
this.outputsHash = "";
|
|
19663
|
+
/**
|
|
19664
|
+
* The proposer's uniqueness salt for this proposal's content-addressed
|
|
19665
|
+
* URI (`ad4m://flow/proposal/<hash>`; the hash covers the instance, the
|
|
19666
|
+
* edge, the seal, the outputs commitment, the proposer DID and this
|
|
19667
|
+
* nonce). The engine writes a UUID. A proposal without one — or whose URI
|
|
19668
|
+
* does not match its own signed fields — is not engine-visible:
|
|
19669
|
+
* co-signatures name the URI, so the URI must commit to what they sign
|
|
19670
|
+
* (#1108).
|
|
19671
|
+
*/
|
|
19672
|
+
this.nonce = "";
|
|
19186
19673
|
// "When was this proposal written?" is answered by `Ad4mModel`'s built-in
|
|
19187
19674
|
// `createdAt`, synthesized on hydration from the earliest link timestamp
|
|
19188
19675
|
// of the proposal's own links (all written together during create_subject).
|
|
@@ -19212,6 +19699,18 @@ __decorate([
|
|
|
19212
19699
|
Property({ through: "ad4m://flow/evidence_hashes", required: true }),
|
|
19213
19700
|
__metadata("design:type", String)
|
|
19214
19701
|
], exports.FlowTransitionProposal.prototype, "evidenceHashes", void 0);
|
|
19702
|
+
__decorate([
|
|
19703
|
+
HasMany({ through: "ad4m://flow/output", datatype: "xsd:string" }),
|
|
19704
|
+
__metadata("design:type", Array)
|
|
19705
|
+
], exports.FlowTransitionProposal.prototype, "outputs", void 0);
|
|
19706
|
+
__decorate([
|
|
19707
|
+
Property({ through: "ad4m://flow/outputs_hash" }),
|
|
19708
|
+
__metadata("design:type", String)
|
|
19709
|
+
], exports.FlowTransitionProposal.prototype, "outputsHash", void 0);
|
|
19710
|
+
__decorate([
|
|
19711
|
+
Property({ through: "ad4m://flow/nonce" }),
|
|
19712
|
+
__metadata("design:type", String)
|
|
19713
|
+
], exports.FlowTransitionProposal.prototype, "nonce", void 0);
|
|
19215
19714
|
__decorate([
|
|
19216
19715
|
Optional({ through: "ad4m://flow/run_uri" }),
|
|
19217
19716
|
__metadata("design:type", String)
|
|
@@ -19271,7 +19770,13 @@ exports.FlowInstanceRecord = class FlowInstanceRecord extends Ad4mModel {
|
|
|
19271
19770
|
* on read.
|
|
19272
19771
|
*/
|
|
19273
19772
|
this.subject = "";
|
|
19274
|
-
/**
|
|
19773
|
+
/**
|
|
19774
|
+
* The state name this replica's executor last derived for the flow — a
|
|
19775
|
+
* per-replica cache written as a `local` link, never the authority (the
|
|
19776
|
+
* fold over the signed proposals is). Optional on the shape: a row that
|
|
19777
|
+
* synced in from a peer carries no value until the local consensus pass
|
|
19778
|
+
* has run, so an empty string means "not yet derived here".
|
|
19779
|
+
*/
|
|
19275
19780
|
this.currentState = "";
|
|
19276
19781
|
// "When was this flow started?" is answered by `Ad4mModel`'s built-in
|
|
19277
19782
|
// `createdAt`, synthesized on hydration from the earliest link timestamp
|
|
@@ -19287,7 +19792,7 @@ __decorate([
|
|
|
19287
19792
|
__metadata("design:type", String)
|
|
19288
19793
|
], exports.FlowInstanceRecord.prototype, "subject", void 0);
|
|
19289
19794
|
__decorate([
|
|
19290
|
-
Property({ through: "ad4m://flow/current_state",
|
|
19795
|
+
Property({ through: "ad4m://flow/current_state", local: true }),
|
|
19291
19796
|
__metadata("design:type", String)
|
|
19292
19797
|
], exports.FlowInstanceRecord.prototype, "currentState", void 0);
|
|
19293
19798
|
exports.FlowInstanceRecord = __decorate([
|
|
@@ -19313,7 +19818,7 @@ exports.FlowInstanceRecord = __decorate([
|
|
|
19313
19818
|
* than the `wrap` escape hatch, which exists for tests that already own
|
|
19314
19819
|
* a matched (record, shape) pair.
|
|
19315
19820
|
*
|
|
19316
|
-
* # What's here
|
|
19821
|
+
* # What's here, and what is still absent
|
|
19317
19822
|
*
|
|
19318
19823
|
* Read surface (implemented today, PR #929):
|
|
19319
19824
|
* - `uri`, `subject`, `flowName`, `currentStateName`, `startedAtMillis`
|
|
@@ -19324,12 +19829,31 @@ exports.FlowInstanceRecord = __decorate([
|
|
|
19324
19829
|
* - `proposals()` — queries `FlowTransitionProposal` records that
|
|
19325
19830
|
* target this instance's URI.
|
|
19326
19831
|
*
|
|
19327
|
-
*
|
|
19328
|
-
*
|
|
19329
|
-
*
|
|
19330
|
-
*
|
|
19331
|
-
*
|
|
19332
|
-
*
|
|
19832
|
+
* - `acceptProposal()` / `rejectProposal()` — the consensus write API:
|
|
19833
|
+
* accept counts your DID toward the flow's consensusRule and fires the
|
|
19834
|
+
* transition at quorum; reject withdraws only the links you signed and
|
|
19835
|
+
* resolves to how many went. Reject is not a cancel — another agent's
|
|
19836
|
+
* proposal is theirs, and because state is recomputed from the links
|
|
19837
|
+
* present now, withdrawing a vote that had settled an edge moves the
|
|
19838
|
+
* flow back to where it stood before it.
|
|
19839
|
+
*
|
|
19840
|
+
* - `proposeTransition()` — the manual write path: propose an edge as this
|
|
19841
|
+
* agent, or co-sign the equivalent proposal another agent already opened.
|
|
19842
|
+
* Its `FlowProposeResult` is what tells queued from no-op from stalled.
|
|
19843
|
+
*
|
|
19844
|
+
* Still absent (rather than shipped as `throw new Error("not yet")`
|
|
19845
|
+
* stubs): `fireAction`, and the subscriptions (`onStateChange`,
|
|
19846
|
+
* `onProposalAdded`, `onProposalResolved`) — they land with the
|
|
19847
|
+
* subscription-topic slice.
|
|
19848
|
+
*
|
|
19849
|
+
* ## The guard-free rule
|
|
19850
|
+
*
|
|
19851
|
+
* A state with no `requires` guard is **never** proposed by the engine, on
|
|
19852
|
+
* any replica, ever — `flow_evaluator`'s auto-proposal composer skips it by
|
|
19853
|
+
* design. Nothing in the graph implies a human started work; they said so.
|
|
19854
|
+
* So states like "in progress" and "in review" only ever advance through
|
|
19855
|
+
* `proposeTransition`. This is a permanent contract, not a gap: wire the
|
|
19856
|
+
* button, or the instance sits there.
|
|
19333
19857
|
*/
|
|
19334
19858
|
/**
|
|
19335
19859
|
* Extract the flow's human-readable name from its canonical URI.
|
|
@@ -19392,9 +19916,15 @@ class FlowInstance {
|
|
|
19392
19916
|
*
|
|
19393
19917
|
* The returned wrapper carries the parsed `SHACLFlow` alongside the
|
|
19394
19918
|
* on-graph record, so `currentState` / `availableTransitions` /
|
|
19395
|
-
* `proposals` accessors work without further round-trips.
|
|
19396
|
-
*
|
|
19397
|
-
*
|
|
19919
|
+
* `proposals` accessors work without further round-trips.
|
|
19920
|
+
*
|
|
19921
|
+
* The record's `currentState` is a per-replica cache the consensus engine
|
|
19922
|
+
* writes as a local link. It is read back only for display — the cache-first
|
|
19923
|
+
* path in `gather_active_flow_contexts` fills the state rendered into LLM
|
|
19924
|
+
* context — and **never as authority**: anything that decides something
|
|
19925
|
+
* (the fold, the mint pass) derives state from the signed links present now
|
|
19926
|
+
* and does not consult the cache. Treat it as a display hint, not as the
|
|
19927
|
+
* flow's state.
|
|
19398
19928
|
*
|
|
19399
19929
|
* @param perspective - The perspective the flow instance lives on
|
|
19400
19930
|
* @param flowName - Name of a `SHACLFlow` already registered on the perspective
|
|
@@ -19554,7 +20084,7 @@ class FlowInstance {
|
|
|
19554
20084
|
* `FlowTransitionProposal.flowInstance` references).
|
|
19555
20085
|
*/
|
|
19556
20086
|
get uri() {
|
|
19557
|
-
return this.record.
|
|
20087
|
+
return this.record.id;
|
|
19558
20088
|
}
|
|
19559
20089
|
/**
|
|
19560
20090
|
* URI of the base expression this flow runs on — matches the
|
|
@@ -19619,14 +20149,53 @@ class FlowInstance {
|
|
|
19619
20149
|
* for the where-filter — one SPARQL round-trip, no client-side
|
|
19620
20150
|
* filtering.
|
|
19621
20151
|
*
|
|
19622
|
-
*
|
|
19623
|
-
*
|
|
20152
|
+
* These are written by the executor's consensus pass when it mints a
|
|
20153
|
+
* transition, and by clients proposing directly. Superseded proposals are
|
|
20154
|
+
* not swept here — a stale one is simply never counted by the fold, and
|
|
20155
|
+
* accepting it fails with a stale-state error.
|
|
19624
20156
|
*/
|
|
19625
20157
|
async proposals() {
|
|
19626
20158
|
return exports.FlowTransitionProposal.findAll(this.perspective, {
|
|
19627
20159
|
where: { flowInstance: this.uri },
|
|
19628
20160
|
});
|
|
19629
20161
|
}
|
|
20162
|
+
/**
|
|
20163
|
+
* Propose a flow transition for this instance, as the calling agent.
|
|
20164
|
+
*
|
|
20165
|
+
* The executor evaluates the guard on its own replica, seals the evidence,
|
|
20166
|
+
* and either writes a new proposal or — when an equivalent one is already
|
|
20167
|
+
* open, i.e. another agent pressed the same button first — co-signs that
|
|
20168
|
+
* one. When the resulting vote reaches the target state's
|
|
20169
|
+
* `consensusRule.n`, the transition fires in the same call.
|
|
20170
|
+
*
|
|
20171
|
+
* How to read the result — fired vs. queued vs. no-op vs. stalled — is
|
|
20172
|
+
* documented on {@link FlowProposeResult} itself.
|
|
20173
|
+
*
|
|
20174
|
+
* `outputs` names the instances the run produces, as `{ className, id }`
|
|
20175
|
+
* pairs, for a transition into a terminal state. The proposal signs a hash
|
|
20176
|
+
* over their content, every co-signer recomputes it on its own replica,
|
|
20177
|
+
* and a receipt for the run speaks for exactly these instances as they
|
|
20178
|
+
* stood at completion.
|
|
20179
|
+
*
|
|
20180
|
+
* Throws when `toState` is not reachable from the derived state, when the
|
|
20181
|
+
* target state carries a `requires` guard that is not currently satisfied
|
|
20182
|
+
* on this replica, when the instance is already contested, when `outputs`
|
|
20183
|
+
* is given for a non-terminal state or names something that is not an
|
|
20184
|
+
* instance of its class, or
|
|
20185
|
+
* when an open proposal on the same edge names different outputs.
|
|
20186
|
+
*/
|
|
20187
|
+
async proposeTransition(toState, rationale, outputs) {
|
|
20188
|
+
return this.perspective.proposeFlowTransition(this.uri, toState, rationale, outputs);
|
|
20189
|
+
}
|
|
20190
|
+
async acceptProposal(proposal) {
|
|
20191
|
+
const uri = typeof proposal === "string" ? proposal : proposal.id;
|
|
20192
|
+
return this.perspective.acceptFlowProposal(uri);
|
|
20193
|
+
}
|
|
20194
|
+
/** Withdraw our own links from a proposal; resolves to how many went. */
|
|
20195
|
+
async rejectProposal(proposal) {
|
|
20196
|
+
const uri = typeof proposal === "string" ? proposal : proposal.id;
|
|
20197
|
+
return this.perspective.rejectFlowProposal(uri);
|
|
20198
|
+
}
|
|
19630
20199
|
}
|
|
19631
20200
|
|
|
19632
20201
|
/**
|
|
@@ -19748,15 +20317,73 @@ function parseLitBoolean(val) {
|
|
|
19748
20317
|
/**
|
|
19749
20318
|
* WakerSubscriptionManager — manages live query subscriptions for the waker.
|
|
19750
20319
|
*
|
|
19751
|
-
*
|
|
19752
|
-
*
|
|
20320
|
+
* This is the single implementation: it is exported from `@coasys/ad4m` and
|
|
20321
|
+
* used by the integration tests, and the OpenClaw AD4M plugin re-exports this
|
|
20322
|
+
* module (`plugins/ad4m/wakerSubscriptionManager.ts`) rather than carrying its
|
|
20323
|
+
* own copy. Any behaviour change belongs here.
|
|
20324
|
+
*/
|
|
20325
|
+
/**
|
|
20326
|
+
* Add a short cause hint to known subscription failures.
|
|
20327
|
+
* The executor needs its main key to register a live query; on a restarted
|
|
20328
|
+
* executor whose wallet was never unlocked this surfaces as a bare 403.
|
|
20329
|
+
*/
|
|
20330
|
+
function hintFor(msg) {
|
|
20331
|
+
// "Executor is locked" is the current executor's message; "main key not
|
|
20332
|
+
// found" is what older executors (and unrelated key lookups) say for the
|
|
20333
|
+
// same locked state. Either way the caller cannot fix it themselves: keys
|
|
20334
|
+
// live in memory only, so every restart locks the node again and only its
|
|
20335
|
+
// operator can unlock it.
|
|
20336
|
+
if (/executor is locked/i.test(msg) || /main key not found/i.test(msg)) {
|
|
20337
|
+
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";
|
|
20338
|
+
}
|
|
20339
|
+
if (/timed out after \d+ms/i.test(msg)) {
|
|
20340
|
+
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";
|
|
20341
|
+
}
|
|
20342
|
+
return "";
|
|
20343
|
+
}
|
|
20344
|
+
/**
|
|
20345
|
+
* Reject `promise` after `ms` instead of waiting forever.
|
|
19753
20346
|
*
|
|
19754
|
-
*
|
|
20347
|
+
* The pending set only catches rejections. A handshake that hangs — the
|
|
20348
|
+
* executor accepted the socket but never answers — settles nothing, so the
|
|
20349
|
+
* subscription was recorded nowhere and the caller's tool invocation died at
|
|
20350
|
+
* the harness timeout instead (#1016). The underlying promise is left as is:
|
|
20351
|
+
* the caller disposes the proxy, so a late answer backs out on its own.
|
|
19755
20352
|
*/
|
|
20353
|
+
async function withTimeout(promise, ms, message) {
|
|
20354
|
+
let timer;
|
|
20355
|
+
try {
|
|
20356
|
+
return await Promise.race([
|
|
20357
|
+
promise,
|
|
20358
|
+
new Promise((_resolve, reject) => {
|
|
20359
|
+
timer = setTimeout(() => reject(new Error(message)), ms);
|
|
20360
|
+
}),
|
|
20361
|
+
]);
|
|
20362
|
+
}
|
|
20363
|
+
finally {
|
|
20364
|
+
if (timer)
|
|
20365
|
+
clearTimeout(timer);
|
|
20366
|
+
}
|
|
20367
|
+
}
|
|
19756
20368
|
class WakerSubscriptionManager {
|
|
19757
20369
|
constructor(options) {
|
|
19758
20370
|
this.proxies = new Map();
|
|
19759
20371
|
this.activeSubscriptions = new Map();
|
|
20372
|
+
/** Subscriptions the executor rejected, waiting to be re-attempted. */
|
|
20373
|
+
this.pendingSubscriptions = new Map();
|
|
20374
|
+
this.retryTimer = null;
|
|
20375
|
+
/**
|
|
20376
|
+
* Cancellation tokens for in-flight `subscribe()` calls.
|
|
20377
|
+
*
|
|
20378
|
+
* `subscribe()` awaits `proxy.subscribe()` and `proxy.initialized`; a
|
|
20379
|
+
* `dispose()` / `disposeAll()` landing during either await used to leave a
|
|
20380
|
+
* live subscription behind, because nothing stopped the resumed call from
|
|
20381
|
+
* registering the proxy in `proxies` / `activeSubscriptions` afterwards.
|
|
20382
|
+
* `epoch` is bumped by `disposeAll()` (which cannot enumerate in-flight
|
|
20383
|
+
* ids), `generations` per id by `dispose()` and by each new `subscribe()`.
|
|
20384
|
+
*/
|
|
20385
|
+
this.epoch = 0;
|
|
20386
|
+
this.generations = new Map();
|
|
19760
20387
|
this.debounceTimers = new Map();
|
|
19761
20388
|
/** Per-subscription set of already-processed message addresses (for mention subs)
|
|
19762
20389
|
* or serialized result hash (for channel-messages subs). */
|
|
@@ -19768,6 +20395,18 @@ class WakerSubscriptionManager {
|
|
|
19768
20395
|
this.onPersist = options.onPersist;
|
|
19769
20396
|
this.QuerySubscriptionProxyCtor = options.QuerySubscriptionProxy ?? null;
|
|
19770
20397
|
this.previousSeenMessages = options.previousSeenMessages ?? {};
|
|
20398
|
+
this.retryPendingMs = options.retryPendingMs ?? 30000;
|
|
20399
|
+
this.subscribeTimeoutMs = options.subscribeTimeoutMs ?? 15000;
|
|
20400
|
+
}
|
|
20401
|
+
/** A token identifying this attempt at subscribing `id`. */
|
|
20402
|
+
beginAttempt(id) {
|
|
20403
|
+
const gen = (this.generations.get(id) ?? 0) + 1;
|
|
20404
|
+
this.generations.set(id, gen);
|
|
20405
|
+
return { epoch: this.epoch, gen };
|
|
20406
|
+
}
|
|
20407
|
+
/** Whether this attempt has been superseded by a dispose or a newer one. */
|
|
20408
|
+
isStale(id, token) {
|
|
20409
|
+
return token.epoch !== this.epoch || this.generations.get(id) !== token.gen;
|
|
19771
20410
|
}
|
|
19772
20411
|
/**
|
|
19773
20412
|
* Create a live SPARQL subscription.
|
|
@@ -19776,6 +20415,7 @@ class WakerSubscriptionManager {
|
|
|
19776
20415
|
async subscribe(sub) {
|
|
19777
20416
|
// Dispose existing subscription with same id if any
|
|
19778
20417
|
this.dispose(sub.id, false);
|
|
20418
|
+
const token = this.beginAttempt(sub.id);
|
|
19779
20419
|
if (!this.QuerySubscriptionProxyCtor) {
|
|
19780
20420
|
throw new Error("WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options");
|
|
19781
20421
|
}
|
|
@@ -19790,9 +20430,24 @@ class WakerSubscriptionManager {
|
|
|
19790
20430
|
if (proxy.initialized && typeof proxy.initialized.catch === "function") {
|
|
19791
20431
|
proxy.initialized.catch(() => { });
|
|
19792
20432
|
}
|
|
20433
|
+
// One deadline for the whole handshake: `proxy.subscribe()` and the
|
|
20434
|
+
// `initialized` promise it resolves share the budget, so a hang in either
|
|
20435
|
+
// surfaces as the same loud-but-recoverable failure a rejection does.
|
|
20436
|
+
const budgetMs = this.subscribeTimeoutMs;
|
|
20437
|
+
const startedAt = Date.now();
|
|
20438
|
+
const bounded = (step, what) => budgetMs > 0
|
|
20439
|
+
? withTimeout(step, Math.max(0, budgetMs - (Date.now() - startedAt)), `${what} timed out after ${budgetMs}ms`)
|
|
20440
|
+
: step;
|
|
19793
20441
|
try {
|
|
19794
|
-
await proxy.subscribe();
|
|
19795
|
-
|
|
20442
|
+
await bounded(proxy.subscribe(), "subscribe handshake");
|
|
20443
|
+
if (this.isStale(sub.id, token)) {
|
|
20444
|
+
try {
|
|
20445
|
+
proxy.dispose();
|
|
20446
|
+
}
|
|
20447
|
+
catch { }
|
|
20448
|
+
return;
|
|
20449
|
+
}
|
|
20450
|
+
await bounded(proxy.initialized, "subscription initialization");
|
|
19796
20451
|
}
|
|
19797
20452
|
catch (err) {
|
|
19798
20453
|
const msg = err?.message ?? String(err);
|
|
@@ -19801,12 +20456,36 @@ class WakerSubscriptionManager {
|
|
|
19801
20456
|
proxy.dispose();
|
|
19802
20457
|
}
|
|
19803
20458
|
catch { }
|
|
19804
|
-
//
|
|
20459
|
+
// A dispose that landed mid-attempt wins: don't re-queue something the
|
|
20460
|
+
// caller has since asked us to forget.
|
|
20461
|
+
if (this.isStale(sub.id, token))
|
|
20462
|
+
return;
|
|
20463
|
+
// Remove from active state — it is not listening, so it must not be
|
|
20464
|
+
// reported as active or persisted as if it were.
|
|
19805
20465
|
this.activeSubscriptions.delete(sub.id);
|
|
19806
20466
|
this.seenMessages.delete(sub.id);
|
|
19807
20467
|
this.persist();
|
|
19808
|
-
|
|
20468
|
+
// Keep it pending and re-attempt: the usual cause (locked wallet, executor
|
|
20469
|
+
// mid-restart, a handshake the executor never answered) clears on its
|
|
20470
|
+
// own, and the caller asked to be enrolled.
|
|
20471
|
+
this.pendingSubscriptions.set(sub.id, sub);
|
|
20472
|
+
this.scheduleRetry();
|
|
20473
|
+
// Throw so callers can report the real outcome. Background callers
|
|
20474
|
+
// (auto-subscribe, restore-on-start) catch and log; the subscribe tools
|
|
20475
|
+
// turn this into an error result instead of a false "Subscribed" reply.
|
|
20476
|
+
throw new Error(`Waker subscription ${sub.id} failed: ${msg}${hintFor(msg)}` +
|
|
20477
|
+
(this.retryPendingMs > 0
|
|
20478
|
+
? `. Not listening yet — re-attempting every ${Math.round(this.retryPendingMs / 1000)}s; check ad4m_list_waker_subscriptions.`
|
|
20479
|
+
: ""));
|
|
20480
|
+
}
|
|
20481
|
+
if (this.isStale(sub.id, token)) {
|
|
20482
|
+
try {
|
|
20483
|
+
proxy.dispose();
|
|
20484
|
+
}
|
|
20485
|
+
catch { }
|
|
20486
|
+
return;
|
|
19809
20487
|
}
|
|
20488
|
+
this.pendingSubscriptions.delete(sub.id);
|
|
19810
20489
|
this.logger.info(`[waker] ${sub.id}: subscription initialized successfully`);
|
|
19811
20490
|
// Seed from persisted seen messages so we don't re-wake after restart
|
|
19812
20491
|
const seen = new Set(this.previousSeenMessages[sub.id] ?? []);
|
|
@@ -19887,16 +20566,72 @@ class WakerSubscriptionManager {
|
|
|
19887
20566
|
}, this.debounceMs));
|
|
19888
20567
|
}
|
|
19889
20568
|
});
|
|
20569
|
+
if (this.isStale(sub.id, token)) {
|
|
20570
|
+
try {
|
|
20571
|
+
proxy.dispose();
|
|
20572
|
+
}
|
|
20573
|
+
catch { }
|
|
20574
|
+
return;
|
|
20575
|
+
}
|
|
19890
20576
|
this.proxies.set(sub.id, proxy);
|
|
19891
20577
|
this.activeSubscriptions.set(sub.id, sub);
|
|
19892
20578
|
this.persist();
|
|
19893
20579
|
this.logger.info(`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`);
|
|
19894
20580
|
}
|
|
20581
|
+
/** Arm the re-attempt timer if pending subscriptions are waiting. */
|
|
20582
|
+
scheduleRetry() {
|
|
20583
|
+
if (this.retryPendingMs <= 0)
|
|
20584
|
+
return;
|
|
20585
|
+
if (this.retryTimer || this.pendingSubscriptions.size === 0)
|
|
20586
|
+
return;
|
|
20587
|
+
this.retryTimer = setTimeout(() => {
|
|
20588
|
+
this.retryTimer = null;
|
|
20589
|
+
void this.retryPending();
|
|
20590
|
+
}, this.retryPendingMs);
|
|
20591
|
+
if (typeof this.retryTimer.unref === "function")
|
|
20592
|
+
this.retryTimer.unref();
|
|
20593
|
+
}
|
|
20594
|
+
/**
|
|
20595
|
+
* Re-attempt every subscription the executor rejected.
|
|
20596
|
+
* Each attempt that fails puts itself back into the pending set and re-arms
|
|
20597
|
+
* the timer, so an agent that asked to be subscribed ends up enrolled once
|
|
20598
|
+
* the executor can accept the query.
|
|
20599
|
+
*/
|
|
20600
|
+
async retryPending() {
|
|
20601
|
+
const waiting = Array.from(this.pendingSubscriptions.values());
|
|
20602
|
+
if (waiting.length === 0)
|
|
20603
|
+
return;
|
|
20604
|
+
this.logger.info(`[waker] re-attempting ${waiting.length} pending subscription(s)`);
|
|
20605
|
+
const epoch = this.epoch;
|
|
20606
|
+
for (const sub of waiting) {
|
|
20607
|
+
// A disposeAll() between two awaits must stop the whole sweep, and a
|
|
20608
|
+
// dispose() of this id must skip just it.
|
|
20609
|
+
if (epoch !== this.epoch)
|
|
20610
|
+
return;
|
|
20611
|
+
if (!this.pendingSubscriptions.has(sub.id))
|
|
20612
|
+
continue;
|
|
20613
|
+
this.pendingSubscriptions.delete(sub.id);
|
|
20614
|
+
try {
|
|
20615
|
+
await this.subscribe(sub);
|
|
20616
|
+
this.logger.info(`[waker] ${sub.id}: enrolled on re-attempt`);
|
|
20617
|
+
}
|
|
20618
|
+
catch (err) {
|
|
20619
|
+
// subscribe() already logged, re-queued and re-armed the timer.
|
|
20620
|
+
this.logger.debug(`[waker] ${sub.id}: still pending — ${err?.message ?? err}`);
|
|
20621
|
+
}
|
|
20622
|
+
}
|
|
20623
|
+
}
|
|
20624
|
+
/** Subscriptions that were rejected and are waiting to be re-attempted. */
|
|
20625
|
+
getPending() {
|
|
20626
|
+
return Array.from(this.pendingSubscriptions.values());
|
|
20627
|
+
}
|
|
19895
20628
|
/**
|
|
19896
20629
|
* Dispose a single subscription.
|
|
19897
20630
|
* @param persist — if false, skip calling onPersist (used during batch cleanup).
|
|
19898
20631
|
*/
|
|
19899
20632
|
dispose(id, persist = true) {
|
|
20633
|
+
// Invalidate any subscribe() for this id that is still awaiting.
|
|
20634
|
+
this.generations.set(id, (this.generations.get(id) ?? 0) + 1);
|
|
19900
20635
|
const proxy = this.proxies.get(id);
|
|
19901
20636
|
if (proxy) {
|
|
19902
20637
|
try {
|
|
@@ -19913,15 +20648,24 @@ class WakerSubscriptionManager {
|
|
|
19913
20648
|
this.debounceTimers.delete(id);
|
|
19914
20649
|
}
|
|
19915
20650
|
this.activeSubscriptions.delete(id);
|
|
20651
|
+
this.pendingSubscriptions.delete(id);
|
|
19916
20652
|
this.seenMessages.delete(id);
|
|
19917
20653
|
if (persist)
|
|
19918
20654
|
this.persist();
|
|
19919
20655
|
}
|
|
19920
|
-
/** Dispose all active subscriptions. */
|
|
20656
|
+
/** Dispose all active subscriptions and drop anything still pending. */
|
|
19921
20657
|
disposeAll() {
|
|
20658
|
+
// Bump the epoch first: in-flight subscribe() calls have no proxy in the
|
|
20659
|
+
// map yet, so per-id invalidation alone cannot reach them.
|
|
20660
|
+
this.epoch++;
|
|
19922
20661
|
for (const [id] of this.proxies) {
|
|
19923
20662
|
this.dispose(id, false);
|
|
19924
20663
|
}
|
|
20664
|
+
this.pendingSubscriptions.clear();
|
|
20665
|
+
if (this.retryTimer) {
|
|
20666
|
+
clearTimeout(this.retryTimer);
|
|
20667
|
+
this.retryTimer = null;
|
|
20668
|
+
}
|
|
19925
20669
|
}
|
|
19926
20670
|
/** Get all active subscriptions. */
|
|
19927
20671
|
getActive() {
|
|
@@ -20019,18 +20763,6 @@ class SmartLiteral {
|
|
|
20019
20763
|
}
|
|
20020
20764
|
_SmartLiteral_perspective = new WeakMap(), _SmartLiteral_base = new WeakMap();
|
|
20021
20765
|
|
|
20022
|
-
/**
|
|
20023
|
-
* Shared type definitions for the Ad4mModel system.
|
|
20024
|
-
*
|
|
20025
|
-
* Extracted into a standalone module so that utility files
|
|
20026
|
-
* (`query-utils.ts`, `decorators.ts`, etc.) can import types without
|
|
20027
|
-
* creating circular runtime dependencies on `Ad4mModel.ts`.
|
|
20028
|
-
*/
|
|
20029
|
-
/** Type guard for IncludeProjection objects. */
|
|
20030
|
-
function isIncludeProjection(val) {
|
|
20031
|
-
return typeof val === 'object' && val !== null && 'from' in val;
|
|
20032
|
-
}
|
|
20033
|
-
|
|
20034
20766
|
/**
|
|
20035
20767
|
* Shared query compilation utilities.
|
|
20036
20768
|
*
|
|
@@ -20087,6 +20819,22 @@ function formatQueryValue(value) {
|
|
|
20087
20819
|
* @returns A single SPARQL condition string
|
|
20088
20820
|
*/
|
|
20089
20821
|
function buildWhereCondition(predicate, condition, opts) {
|
|
20822
|
+
// `{ eq: X }` is the bare `X`. A nested `author` is a per-link condition
|
|
20823
|
+
// the executor answers in model queries; a getter's SPARQL has no reifier
|
|
20824
|
+
// join to answer it with, so it is refused rather than dropped (#1114).
|
|
20825
|
+
if (typeof condition === 'object' && condition !== null && !Array.isArray(condition)) {
|
|
20826
|
+
const ops = condition;
|
|
20827
|
+
if (ops.author !== undefined) {
|
|
20828
|
+
throw new Error(`buildWhereCondition: a nested \`author\` on <${predicate}> is a per-link condition ` +
|
|
20829
|
+
'that only the model query path can answer');
|
|
20830
|
+
}
|
|
20831
|
+
if (ops.eq !== undefined) {
|
|
20832
|
+
if (Object.keys(ops).some((k) => k !== 'eq')) {
|
|
20833
|
+
throw new Error(`buildWhereCondition: \`eq\` on <${predicate}> cannot be combined with another operator`);
|
|
20834
|
+
}
|
|
20835
|
+
condition = ops.eq;
|
|
20836
|
+
}
|
|
20837
|
+
}
|
|
20090
20838
|
const escapedPredicate = escapeQueryString(predicate);
|
|
20091
20839
|
// For deterministic-literal properties, values are stored as typed
|
|
20092
20840
|
// literals like `"X"^^xsd:string` (or the legacy `<literal:string:VALUE>`
|
|
@@ -20505,6 +21253,7 @@ exports.getPropertiesMetadata = getPropertiesMetadata;
|
|
|
20505
21253
|
exports.getPropertyOption = getPropertyOption;
|
|
20506
21254
|
exports.getRelationsMetadata = getRelationsMetadata;
|
|
20507
21255
|
exports.hasJsOnlyWhereFilters = hasJsOnlyWhereFilters;
|
|
21256
|
+
exports.hintFor = hintFor;
|
|
20508
21257
|
exports.ifExpr = ifExpr;
|
|
20509
21258
|
exports.invalidatePerspectiveCache = invalidatePerspectiveCache;
|
|
20510
21259
|
exports.isArrayType = isArrayType;
|
|
@@ -20515,12 +21264,14 @@ exports.isNodeExpression = isNodeExpression;
|
|
|
20515
21264
|
exports.isNumericType = isNumericType;
|
|
20516
21265
|
exports.isObjectType = isObjectType;
|
|
20517
21266
|
exports.isSchemaType = isSchemaType;
|
|
21267
|
+
exports.isTraverseScope = isTraverseScope;
|
|
20518
21268
|
exports.linkEqual = linkEqual;
|
|
20519
21269
|
exports.literal = literal;
|
|
20520
21270
|
exports.looksLikeUri = looksLikeUri;
|
|
20521
21271
|
exports.normalizeNamespaceString = normalizeNamespaceString;
|
|
20522
21272
|
exports.normalizeSchemaType = normalizeSchemaType;
|
|
20523
21273
|
exports.normalizeValue = normalizeValue;
|
|
21274
|
+
exports.normalizeWhereForSparql = normalizeWhereForSparql;
|
|
20524
21275
|
exports.parseExprUrl = parseExprUrl;
|
|
20525
21276
|
exports.parseLit = parseLit;
|
|
20526
21277
|
exports.parseLitBoolean = parseLitBoolean;
|
|
@@ -20528,6 +21279,7 @@ exports.parseLitNumber = parseLitNumber;
|
|
|
20528
21279
|
exports.parseSparqlCount = parseSparqlCount;
|
|
20529
21280
|
exports.path = path;
|
|
20530
21281
|
exports.queryCacheSize = queryCacheSize;
|
|
21282
|
+
exports.requireSingleParent = requireSingleParent;
|
|
20531
21283
|
exports.resolveParentPredicate = resolveParentPredicate;
|
|
20532
21284
|
exports.setCachedResult = setCachedResult;
|
|
20533
21285
|
exports.setPropertyRegistryEntry = setPropertyRegistryEntry;
|