@coasys/ad4m 0.13.0-test-9 → 0.13.0-test-interpretation

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 +368 -8
  2. package/lib/index.js +369 -9
  3. package/lib/src/ai/AIClient.js +3 -1
  4. package/lib/src/apiClient.d.ts +4 -1
  5. package/lib/src/apiClient.js +7 -3
  6. package/lib/src/generated/api/RunInterpretationRequest.d.ts +19 -0
  7. package/lib/src/generated/api/RunInterpretationRequest.js +1 -0
  8. package/lib/src/generated/api/TranscriptTurn.d.ts +7 -0
  9. package/lib/src/generated/api/TranscriptTurn.js +2 -0
  10. package/lib/src/generated/api/index.d.ts +2 -0
  11. package/lib/src/index.d.ts +2 -0
  12. package/lib/src/index.js +2 -0
  13. package/lib/src/model/ModelQueryBuilder.js +1 -1
  14. package/lib/src/model/decorators.d.ts +25 -0
  15. package/lib/src/model/decorators.js +1 -1
  16. package/lib/src/model/shacl-gen.d.ts +8 -1
  17. package/lib/src/model/shacl-gen.js +21 -1
  18. package/lib/src/perspectives/AutoProcessor.d.ts +89 -0
  19. package/lib/src/perspectives/AutoProcessor.js +5 -0
  20. package/lib/src/perspectives/InterpretationModels.d.ts +71 -0
  21. package/lib/src/perspectives/InterpretationModels.js +190 -0
  22. package/lib/src/perspectives/PerspectiveClient.d.ts +37 -0
  23. package/lib/src/perspectives/PerspectiveClient.js +54 -0
  24. package/lib/src/perspectives/PerspectiveProxy.d.ts +43 -1
  25. package/lib/src/perspectives/PerspectiveProxy.js +53 -1
  26. package/lib/src/shacl/SHACLShape.d.ts +14 -0
  27. package/lib/src/shacl/SHACLShape.js +43 -0
  28. package/package.json +6 -2
  29. package/src/ai/AIClient.ts +3 -1
  30. package/src/apiClient.ts +7 -3
  31. package/src/generated/api/RunInterpretationRequest.ts +18 -0
  32. package/src/generated/api/TranscriptTurn.ts +6 -0
  33. package/src/generated/api/index.ts +2 -0
  34. package/src/index.ts +2 -0
  35. package/src/model/ModelQueryBuilder.ts +1 -1
  36. package/src/model/decorators.ts +29 -0
  37. package/src/model/shacl-gen.ts +22 -0
  38. package/src/model/shacl-roundtrip.test.ts +76 -0
  39. package/src/perspectives/AutoProcessor.ts +107 -0
  40. package/src/perspectives/InterpretationModels.ts +145 -0
  41. package/src/perspectives/PerspectiveClient.ts +75 -0
  42. package/src/perspectives/PerspectiveProxy.ts +61 -1
  43. package/src/shacl/SHACLShape.ts +80 -4
package/lib/index.js CHANGED
@@ -163,20 +163,24 @@ class ApiClient {
163
163
  * Send an RPC call over the WebSocket connection.
164
164
  * @param type - The operation type (e.g. 'agent.get', 'perspective.all')
165
165
  * @param params - Optional parameters to include in the message
166
+ * @param timeoutMs - Optional per-call timeout override in ms. Defaults to
167
+ * [[DEFAULT_TIMEOUT_MS]]. Use for long-running calls (LLM prompts,
168
+ * holochain ops) that legitimately exceed the default.
166
169
  * @returns Promise that resolves with the result from the server
167
170
  */
168
- async call(type, params) {
171
+ async call(type, params, timeoutMs) {
169
172
  await this._ready();
170
173
  const id = nextId();
171
174
  // Put params under a "params" key to avoid collision with
172
175
  // protocol fields "id" and "type" (e.g. params might contain
173
176
  // { id: modelId } or { type: "db" }).
174
177
  const message = { id, type, params: params || {} };
178
+ const effectiveTimeout = timeoutMs ?? DEFAULT_TIMEOUT_MS;
175
179
  return new Promise((resolve, reject) => {
176
180
  const timer = setTimeout(() => {
177
181
  this._pendingCalls.delete(id);
178
- reject(new RpcError(408, `RPC call '${type}' timed out after ${DEFAULT_TIMEOUT_MS}ms`));
179
- }, DEFAULT_TIMEOUT_MS);
182
+ reject(new RpcError(408, `RPC call '${type}' timed out after ${effectiveTimeout}ms`));
183
+ }, effectiveTimeout);
180
184
  this._pendingCalls.set(id, {
181
185
  resolve: resolve,
182
186
  reject,
@@ -1229,6 +1233,15 @@ class SHACLShape {
1229
1233
  target: `literal:string:${JSON.stringify(this.destructor_actions)}`
1230
1234
  });
1231
1235
  }
1236
+ // Class-level interpretation hint — read by the Rust model query as
1237
+ // `ModelShape.interpretation_hint` and fed to the generic LLM extractor.
1238
+ if (this.interpretationHint) {
1239
+ links.push({
1240
+ source: this.nodeShapeUri,
1241
+ predicate: "ad4m://interpretation_hint",
1242
+ target: `literal:string:${this.interpretationHint}`
1243
+ });
1244
+ }
1232
1245
  // Property shapes (each gets a named URI: {namespace}/{ClassName}.{propertyName})
1233
1246
  for (let i = 0; i < this.properties.length; i++) {
1234
1247
  const prop = this.properties[i];
@@ -1428,6 +1441,20 @@ class SHACLShape {
1428
1441
  target: `literal:string:${JSON.stringify(prop.transform)}`
1429
1442
  });
1430
1443
  }
1444
+ if (prop.interpretationHint) {
1445
+ links.push({
1446
+ source: propShapeId,
1447
+ predicate: "ad4m://interpretation_hint",
1448
+ target: `literal:string:${prop.interpretationHint}`
1449
+ });
1450
+ }
1451
+ if (prop.identity) {
1452
+ links.push({
1453
+ source: propShapeId,
1454
+ predicate: "ad4m://identity",
1455
+ target: `literal:string:true`
1456
+ });
1457
+ }
1431
1458
  }
1432
1459
  return links;
1433
1460
  }
@@ -1460,6 +1487,11 @@ class SHACLShape {
1460
1487
  // Ignore parse errors
1461
1488
  }
1462
1489
  }
1490
+ // Class-level interpretation hint (mirror of the emit in toLinks())
1491
+ const classHintLink = links.find(l => l.source === shapeUri && l.predicate === "ad4m://interpretation_hint");
1492
+ if (classHintLink) {
1493
+ shape.interpretationHint = classHintLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1494
+ }
1463
1495
  // Find all property shapes
1464
1496
  const propShapeLinks = links.filter(l => l.source === shapeUri && l.predicate === "sh://property");
1465
1497
  for (const propLink of propShapeLinks) {
@@ -1647,6 +1679,15 @@ class SHACLShape {
1647
1679
  val = val.substring(8);
1648
1680
  prop.filter = val === 'true';
1649
1681
  }
1682
+ const interpretationHintLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://interpretation_hint");
1683
+ if (interpretationHintLink) {
1684
+ prop.interpretationHint = interpretationHintLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1685
+ }
1686
+ const identityLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://identity");
1687
+ if (identityLink) {
1688
+ prop.identity =
1689
+ identityLink.target.replace(/^literal:\/\/string:|^literal:string:/, '') === 'true';
1690
+ }
1650
1691
  const transformLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://transform");
1651
1692
  if (transformLink) {
1652
1693
  const jsonStr = transformLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
@@ -1678,6 +1719,7 @@ class SHACLShape {
1678
1719
  node_shape_uri: this.nodeShapeUri,
1679
1720
  target_class: this.targetClass,
1680
1721
  parent_shapes: this.parentShapes.length > 0 ? this.parentShapes : undefined,
1722
+ interpretation_hint: this.interpretationHint,
1681
1723
  properties: this.properties.map(p => ({
1682
1724
  path: p.path,
1683
1725
  name: p.name,
@@ -1705,6 +1747,7 @@ class SHACLShape {
1705
1747
  where_predicates: p.wherePredicates,
1706
1748
  filter: p.filter,
1707
1749
  transform: p.transform,
1750
+ interpretation_hint: p.interpretationHint,
1708
1751
  })),
1709
1752
  constructor_actions: this.constructor_actions,
1710
1753
  destructor_actions: this.destructor_actions,
@@ -1750,6 +1793,7 @@ class SHACLShape {
1750
1793
  wherePredicates: p.where_predicates,
1751
1794
  filter: p.filter,
1752
1795
  transform: p.transform,
1796
+ interpretationHint: p.interpretation_hint,
1753
1797
  });
1754
1798
  }
1755
1799
  if (json.constructor_actions) {
@@ -1763,6 +1807,9 @@ class SHACLShape {
1763
1807
  shape.addParentShape(ps);
1764
1808
  }
1765
1809
  }
1810
+ if (json.interpretation_hint) {
1811
+ shape.interpretationHint = json.interpretation_hint;
1812
+ }
1766
1813
  return shape;
1767
1814
  }
1768
1815
  }
@@ -1797,7 +1844,14 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
1797
1844
  * `getMemoizedSHACL`; safe to omit when calling `buildSHACL`
1798
1845
  * directly (e.g. from a one-off SDNA build tool).
1799
1846
  */
1800
- seedCache) {
1847
+ seedCache,
1848
+ /**
1849
+ * Natural-language hint declared on the `@Model` decorator that
1850
+ * steers the generic LLM extractor when producing instances of
1851
+ * this class. Attached to the SHACL shape node and re-emitted as
1852
+ * an `ad4m://interpretation_hint` link by `SHACLShape.toLinks()`.
1853
+ */
1854
+ interpretationHint) {
1801
1855
  const obj = target.prototype;
1802
1856
  // ── Determine namespace from first property or relation ─────────────
1803
1857
  let namespace = "ad4m://";
@@ -1825,6 +1879,9 @@ seedCache) {
1825
1879
  const shapeUri = `${namespace}${subjectName}Shape`;
1826
1880
  const targetClass = `${namespace}${subjectName}`;
1827
1881
  const shape = new SHACLShape(shapeUri, targetClass);
1882
+ if (interpretationHint) {
1883
+ shape.interpretationHint = interpretationHint;
1884
+ }
1828
1885
  // ── Seed the memoisation cache while we keep building ──────────────
1829
1886
  // Any subsequent `target.generateSHACL()` call from inside this
1830
1887
  // function (typically when walking a self-referential or
@@ -1911,6 +1968,16 @@ seedCache) {
1911
1968
  if (propMeta.transform) {
1912
1969
  propShape.transform = propMeta.transform;
1913
1970
  }
1971
+ // Natural-language interpretation hint (read by the generic LLM
1972
+ // extractor via ShapeProperty.interpretation_hint).
1973
+ if (propMeta.interpretationHint) {
1974
+ propShape.interpretationHint = propMeta.interpretationHint;
1975
+ }
1976
+ // Declared-identity dedup key for the generic LLM interpreter
1977
+ // (emitted as `ad4m://identity` by SHACLShape.toLinks()).
1978
+ if (propMeta.identity) {
1979
+ propShape.identity = true;
1980
+ }
1914
1981
  // ── Setter actions ──────────────────────────────────────────────
1915
1982
  if (propMeta.prologSetter) {
1916
1983
  console.warn(`[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
@@ -2555,7 +2622,7 @@ function Model$1(opts) {
2555
2622
  return buildSDNA(opts.name, target.prototype, getPropertiesMetadata(target), getRelationsMetadata(target));
2556
2623
  };
2557
2624
  target.generateSHACL = function () {
2558
- return getMemoizedSHACL(target, (seed) => buildSHACL(opts.name, target, getPropertiesMetadata(target), getRelationsMetadata(target), buildConformanceFilter, seed));
2625
+ return getMemoizedSHACL(target, (seed) => buildSHACL(opts.name, target, getPropertiesMetadata(target), getRelationsMetadata(target), buildConformanceFilter, seed, opts.interpretationHint));
2559
2626
  };
2560
2627
  Object.defineProperty(target, 'type', { configurable: true });
2561
2628
  };
@@ -3781,6 +3848,58 @@ class PerspectiveProxy {
3781
3848
  async get(query) {
3782
3849
  return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
3783
3850
  }
3851
+ /**
3852
+ * Runs generic LLM interpretation over a conversation transcript, turning it
3853
+ * into typed instances of this perspective's own SHACL subject classes
3854
+ * (steered by each class's `@InterpretationHint`). The target shapes are
3855
+ * resolved automatically from the perspective's registered classes, so you
3856
+ * pass only the transcript. New instances are written as links into this
3857
+ * perspective; the returned placements list each instance's base URI and
3858
+ * the links written for it.
3859
+ *
3860
+ * @param transcript ordered `{ speaker, text }` turns
3861
+ * @param basePrefix URI namespace for new instance identities, e.g. `soa://ext/`
3862
+ * @param classes local names of the subject classes to extract into; omit for all
3863
+ */
3864
+ async runInterpretation(transcript, basePrefix, classes) {
3865
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").runInterpretation(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, transcript, basePrefix, classes);
3866
+ }
3867
+ /**
3868
+ * Register a neighbourhood auto-processor on this perspective. The executor
3869
+ * then runs interpretation automatically over new source items (like Flux
3870
+ * per channel), coordinating which peer processes each batch. Returns the
3871
+ * processor id. Subscribe to progress via {@link addAutoProcessorEventListener}.
3872
+ */
3873
+ async addAutoProcessor(config) {
3874
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addAutoProcessor(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, config);
3875
+ }
3876
+ /**
3877
+ * Pending interpretation overlays on this perspective — LLM suggestions the
3878
+ * §4 divergence gate staged rather than applied, awaiting human accept/reject.
3879
+ */
3880
+ async interpretationOverlays() {
3881
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").interpretationOverlays(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
3882
+ }
3883
+ /**
3884
+ * Accept an interpretation overlay's suggestion(s): the LLM's staged value
3885
+ * becomes the real, human-owned value and the overlay is deleted. Pass
3886
+ * `property` to accept a single predicate; omit it for the whole base.
3887
+ */
3888
+ async acceptInterpretation(base, property) {
3889
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").acceptInterpretation(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, base, property);
3890
+ }
3891
+ /**
3892
+ * Reject an interpretation overlay's suggestion(s). Omit `property` to reject
3893
+ * the whole base — a rejected `create` deletes the suggested instance, a
3894
+ * rejected `update` drops the overlay and keeps the real value.
3895
+ */
3896
+ async rejectInterpretation(base, property) {
3897
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").rejectInterpretation(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, base, property);
3898
+ }
3899
+ /** Subscribe to this perspective's auto-processor step signals. */
3900
+ async addAutoProcessorEventListener(cb) {
3901
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addAutoProcessorEventListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, cb);
3902
+ }
3784
3903
  /**
3785
3904
  * Executes a Prolog query against the perspective's knowledge base.
3786
3905
  * This is a powerful way to find complex patterns in the graph.
@@ -3865,7 +3984,7 @@ class PerspectiveProxy {
3865
3984
  * internally in Rust, registers a subscription, runs the initial query, and
3866
3985
  * pushes updated results when relevant links change.
3867
3986
  *
3868
- * The subscription reuses the same GraphQL subscription channel as subscribeQuery().
3987
+ * The subscription reuses the same WS-RPC subscription channel as subscribeQuery().
3869
3988
  * Use keepAliveQuery() / disposeQuerySubscription() with the returned subscriptionId.
3870
3989
  *
3871
3990
  * @param className - The model class name
@@ -5611,6 +5730,60 @@ class PerspectiveClient {
5611
5730
  async linkMutations(uuid, mutations, status) {
5612
5731
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.linkMutations', { uuid, mutations, status });
5613
5732
  }
5733
+ /**
5734
+ * Run generic LLM interpretation over a transcript into this perspective's own
5735
+ * SHACL subject classes. The target shapes are resolved server-side from the
5736
+ * perspective's registered subject classes, so you pass only the transcript.
5737
+ * Returns the freshly minted instances (their base URIs + the links written).
5738
+ *
5739
+ * The server-side call prompts an LLM (up to `INTERPRETATION_MAX_ATTEMPTS`
5740
+ * retries on parse failure), so it can legitimately take minutes on slower
5741
+ * or CPU-only models. We raise the default 30s RPC timeout here to 20 min
5742
+ * (matches the CI `--timeout 1200000` for the interpretation tests).
5743
+ */
5744
+ async runInterpretation(uuid, transcript, basePrefix, classes) {
5745
+ const RUN_INTERPRETATION_TIMEOUT_MS = 20 * 60 * 1000;
5746
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretation', { uuid, transcript, basePrefix, classes }, RUN_INTERPRETATION_TIMEOUT_MS);
5747
+ }
5748
+ /**
5749
+ * Register a neighbourhood auto-processor on this perspective. The executor's
5750
+ * watch loop then runs interpretation automatically over new source items
5751
+ * (like Flux per channel), coordinating which peer processes each batch via
5752
+ * the shared-graph ProcessingClaim, and emits step signals on the events
5753
+ * WebSocket (subscribe via {@link addAutoProcessorEventListener}).
5754
+ * Returns the processor id.
5755
+ */
5756
+ async addAutoProcessor(uuid, config) {
5757
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.addAutoProcessor', { uuid, ...config });
5758
+ }
5759
+ /** Pending interpretation overlays (LLM suggestions awaiting human accept/reject). */
5760
+ async interpretationOverlays(uuid) {
5761
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.interpretationOverlays', { uuid });
5762
+ }
5763
+ /** Accept an overlay's suggestion(s): the LLM value becomes the real value and
5764
+ * the overlay is deleted. Omit `property` to accept the whole base. */
5765
+ async acceptInterpretation(uuid, base, property) {
5766
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.acceptInterpretation', { uuid, base, property });
5767
+ }
5768
+ /** Reject an overlay's suggestion(s). Omit `property` to reject the whole base
5769
+ * (a rejected `create` deletes the suggested instance). */
5770
+ async rejectInterpretation(uuid, base, property) {
5771
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectInterpretation', { uuid, base, property });
5772
+ }
5773
+ /**
5774
+ * Subscribe to auto-processor step signals. `cb` fires for every
5775
+ * `auto-processor-event` on `uuid` (BatchReady → Claimed/BackedOff/… →
5776
+ * Processed), letting a UI show progress and await the next batch.
5777
+ */
5778
+ async addAutoProcessorEventListener(uuid, cb) {
5779
+ const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
5780
+ if (data.type === 'auto-processor-event' && data.perspectiveUuid === uuid) {
5781
+ cb(data);
5782
+ }
5783
+ });
5784
+ __classPrivateFieldGet$9(this, _PerspectiveClient_unsubscribers, "f").push(unsub);
5785
+ await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").waitForSubscription();
5786
+ }
5614
5787
  async addLinkExpression(uuid, link, status = 'shared', batchId) {
5615
5788
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.addLinkExpression', { uuid, link, status, batchId });
5616
5789
  }
@@ -13938,7 +14111,9 @@ class AIClient {
13938
14111
  async embed(modelId, text) {
13939
14112
  const aiEmbed = await __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.embed', { modelId, text });
13940
14113
  const compressed = base64Js.toByteArray(aiEmbed);
13941
- const decompressed = JSON.parse(pako.inflate(compressed, { to: 'string' }));
14114
+ // Decode to a string via TextDecoder rather than pako's `{ to: 'string' }`
14115
+ // option: newer @types/pako dropped that overload, which broke the build.
14116
+ const decompressed = JSON.parse(new TextDecoder().decode(pako.inflate(compressed)));
13942
14117
  return decompressed;
13943
14118
  }
13944
14119
  async openTranscriptionStream(modelId, streamCallback, params) {
@@ -15171,7 +15346,7 @@ class ModelQueryBuilder {
15171
15346
  return JSON.stringify(results, (_, v) => typeof v === 'function' ? undefined : v);
15172
15347
  };
15173
15348
  lastResultFingerprint = buildFingerprint(initialResults);
15174
- // Listen for subscription updates via the same GraphQL subscription channel.
15349
+ // Listen for subscription updates via the same WS-RPC subscription channel.
15175
15350
  // When Rust re-runs the model query and finds changed results, it pushes them.
15176
15351
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
15177
15352
  try {
@@ -17544,6 +17719,191 @@ class PerspectiveHandle {
17544
17719
  }
17545
17720
  }
17546
17721
 
17722
+ /**
17723
+ * TypeScript @Model classes mirroring the Rust-side SDNA for the generic
17724
+ * interpretation subsystem. Apps can import these to query the perspective
17725
+ * graph for interpretation history and pending overlay proposals without
17726
+ * knowing the raw link predicates.
17727
+ *
17728
+ * Registration:
17729
+ * await InterpretationOverlay.register(perspective);
17730
+ * await InterpretationRun.register(perspective);
17731
+ * await AutoProcessorConfig.register(perspective);
17732
+ *
17733
+ * Querying:
17734
+ * const pending = await InterpretationOverlay.findAll(perspective);
17735
+ * const runs = await InterpretationRun.findAll(perspective);
17736
+ * const configs = await AutoProcessorConfig.findAll(perspective);
17737
+ */
17738
+ var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
17739
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17740
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
17741
+ 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;
17742
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
17743
+ };
17744
+ var __metadata = (undefined && undefined.__metadata) || function (k, v) {
17745
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
17746
+ };
17747
+ // ── AutoProcessorConfig ─────────────────────────────────────────────────────
17748
+ // Mirrors the Rust `auto_processor::config::AutoProcessorConfig` SDNA.
17749
+ // One node per registered processor; the node URI is
17750
+ // `ad4m://autoprocessor/<processorId>`.
17751
+ let AutoProcessorConfig = class AutoProcessorConfig extends Ad4mModel {
17752
+ constructor() {
17753
+ super(...arguments);
17754
+ this.type = "ad4m://AutoProcessor";
17755
+ /** Unique processor id — the dedup key for auto-processor instances. */
17756
+ this.processorId = "";
17757
+ /** SPARQL SELECT that gathers source items each pass. */
17758
+ this.sourceScopeQuery = "";
17759
+ /** Class URIs (SHACL targetClass) to materialise each pass. */
17760
+ this.interpretationClasses = [];
17761
+ /** Quiet-window (ms) after the last new item before a pass runs. */
17762
+ this.debounceMs = "200";
17763
+ /** Maximum items per pass. */
17764
+ this.batchMax = "32";
17765
+ /** How long a won claim is authoritative before peers may re-claim (ms). */
17766
+ this.claimTtlMs = "60000";
17767
+ }
17768
+ };
17769
+ __decorate([
17770
+ Flag({ through: "rdf://type", value: "ad4m://AutoProcessor" }),
17771
+ __metadata("design:type", String)
17772
+ ], AutoProcessorConfig.prototype, "type", void 0);
17773
+ __decorate([
17774
+ Property({ through: "ad4m://processor_id", required: true, identity: true }),
17775
+ __metadata("design:type", String)
17776
+ ], AutoProcessorConfig.prototype, "processorId", void 0);
17777
+ __decorate([
17778
+ Property({ through: "ad4m://source_scope_query", required: true }),
17779
+ __metadata("design:type", String)
17780
+ ], AutoProcessorConfig.prototype, "sourceScopeQuery", void 0);
17781
+ __decorate([
17782
+ Optional({ through: "ad4m://base_prefix", resolveLanguage: "literal" }),
17783
+ __metadata("design:type", String)
17784
+ ], AutoProcessorConfig.prototype, "basePrefix", void 0);
17785
+ __decorate([
17786
+ HasMany({ through: "ad4m://interpretation_class" }),
17787
+ __metadata("design:type", Array)
17788
+ ], AutoProcessorConfig.prototype, "interpretationClasses", void 0);
17789
+ __decorate([
17790
+ Property({ through: "ad4m://debounce_ms", required: true }),
17791
+ __metadata("design:type", String)
17792
+ ], AutoProcessorConfig.prototype, "debounceMs", void 0);
17793
+ __decorate([
17794
+ Optional({ through: "ad4m://batch_min", resolveLanguage: "literal" }),
17795
+ __metadata("design:type", String)
17796
+ ], AutoProcessorConfig.prototype, "batchMin", void 0);
17797
+ __decorate([
17798
+ Property({ through: "ad4m://batch_max", required: true }),
17799
+ __metadata("design:type", String)
17800
+ ], AutoProcessorConfig.prototype, "batchMax", void 0);
17801
+ __decorate([
17802
+ Optional({ through: "ad4m://max_wait_ms", resolveLanguage: "literal" }),
17803
+ __metadata("design:type", String)
17804
+ ], AutoProcessorConfig.prototype, "maxWaitMs", void 0);
17805
+ __decorate([
17806
+ Property({ through: "ad4m://claim_ttl_ms", required: true }),
17807
+ __metadata("design:type", String)
17808
+ ], AutoProcessorConfig.prototype, "claimTtlMs", void 0);
17809
+ __decorate([
17810
+ Optional({ through: "ad4m://source_window_ms", resolveLanguage: "literal" }),
17811
+ __metadata("design:type", String)
17812
+ ], AutoProcessorConfig.prototype, "sourceWindowMs", void 0);
17813
+ __decorate([
17814
+ Optional({ through: "ad4m://dedup_strategy", resolveLanguage: "literal" }),
17815
+ __metadata("design:type", String)
17816
+ ], AutoProcessorConfig.prototype, "dedupStrategy", void 0);
17817
+ AutoProcessorConfig = __decorate([
17818
+ Model$1({ name: "AutoProcessorConfig" })
17819
+ ], AutoProcessorConfig);
17820
+ // ── InterpretationRun ───────────────────────────────────────────────────────
17821
+ // Mirrors the Rust `interpretation::overlay::InterpretationRun` SDNA.
17822
+ // One node per completed pass; the node URI is `ad4m://interp/run/<runId>`.
17823
+ let InterpretationRun = class InterpretationRun extends Ad4mModel {
17824
+ constructor() {
17825
+ super(...arguments);
17826
+ this.type = "ad4m://interpretation-run";
17827
+ /** UUID for this run — the dedup key across run nodes. */
17828
+ this.runId = "";
17829
+ /**
17830
+ * Source item IDs consumed by this pass.
17831
+ * Stored as multiple links with the same predicate; the processed-turn
17832
+ * cursor uses these to avoid re-interpreting a turn.
17833
+ */
17834
+ this.sources = [];
17835
+ }
17836
+ };
17837
+ __decorate([
17838
+ Flag({ through: "ad4m://type", value: "ad4m://interpretation-run" }),
17839
+ __metadata("design:type", String)
17840
+ ], InterpretationRun.prototype, "type", void 0);
17841
+ __decorate([
17842
+ Property({ through: "ad4m://interp/run_id", required: true, identity: true }),
17843
+ __metadata("design:type", String)
17844
+ ], InterpretationRun.prototype, "runId", void 0);
17845
+ __decorate([
17846
+ Optional({ through: "ad4m://interp/model", resolveLanguage: "literal" }),
17847
+ __metadata("design:type", String)
17848
+ ], InterpretationRun.prototype, "model", void 0);
17849
+ __decorate([
17850
+ Optional({ through: "ad4m://interp/prompt_version", resolveLanguage: "literal" }),
17851
+ __metadata("design:type", String)
17852
+ ], InterpretationRun.prototype, "promptVersion", void 0);
17853
+ __decorate([
17854
+ Optional({ through: "ad4m://interp/ran_at", resolveLanguage: "literal" }),
17855
+ __metadata("design:type", String)
17856
+ ], InterpretationRun.prototype, "ranAt", void 0);
17857
+ __decorate([
17858
+ Optional({ through: "ad4m://interp/processor", resolveLanguage: "literal" }),
17859
+ __metadata("design:type", String)
17860
+ ], InterpretationRun.prototype, "processor", void 0);
17861
+ __decorate([
17862
+ HasMany({ through: "ad4m://interp/sources" }),
17863
+ __metadata("design:type", Array)
17864
+ ], InterpretationRun.prototype, "sources", void 0);
17865
+ InterpretationRun = __decorate([
17866
+ Model$1({ name: "InterpretationRun" })
17867
+ ], InterpretationRun);
17868
+ // ── InterpretationOverlay ───────────────────────────────────────────────────
17869
+ // Mirrors the Rust `interpretation::overlay::InterpretationOverlay` SDNA.
17870
+ // An overlay sits on the *same* base URI as the proposed instance — it is a
17871
+ // pending LLM suggestion awaiting human accept/reject.
17872
+ //
17873
+ // The dynamic "inferred" values are stored as links with predicates of the
17874
+ // form `ad4m://interp/inferred/<realPredicate>` and are NOT captured here as
17875
+ // fixed @Property fields because the predicates vary per class. Read them
17876
+ // directly via perspective.get({ source: overlay.baseExpression }).
17877
+ //
17878
+ // Accept → perspective.acceptInterpretationOverlay(base) [deletes the overlay]
17879
+ // Reject → perspective.rejectInterpretationOverlay(base) [drops the suggestion]
17880
+ //
17881
+ // Note: `findAll` finds ALL nodes that currently carry a `kind` link, i.e.
17882
+ // all pending proposals. Accepted/rejected overlays are removed from the
17883
+ // graph and will not appear.
17884
+ let InterpretationOverlay = class InterpretationOverlay extends Ad4mModel {
17885
+ constructor() {
17886
+ super(...arguments);
17887
+ /**
17888
+ * Whether the LLM authored the whole instance (`"create"`) or proposed
17889
+ * changes to an existing one (`"update"`). This is the discriminator link
17890
+ * that makes a node identifiable as an overlay.
17891
+ */
17892
+ this.kind = "";
17893
+ }
17894
+ };
17895
+ __decorate([
17896
+ Property({ through: "ad4m://interp/kind", required: true, resolveLanguage: "literal" }),
17897
+ __metadata("design:type", String)
17898
+ ], InterpretationOverlay.prototype, "kind", void 0);
17899
+ __decorate([
17900
+ Optional({ through: "ad4m://interp/run", resolveLanguage: "literal" }),
17901
+ __metadata("design:type", String)
17902
+ ], InterpretationOverlay.prototype, "run", void 0);
17903
+ InterpretationOverlay = __decorate([
17904
+ Model$1({ name: "InterpretationOverlay" })
17905
+ ], InterpretationOverlay);
17906
+
17547
17907
  /**
17548
17908
  * SPARQL binding helpers — typed shapes and parsers for `querySparql<T>()`.
17549
17909
  *
@@ -18222,4 +18582,4 @@ const fileToDataUri = ifExpr(exists(path('file_storage://data_base64')))
18222
18582
  .then(concat(literal('data:'), coalesce(path('file_storage://file_type'), literal('image/png')), literal(';base64,'), path('file_storage://data_base64')))
18223
18583
  .else(focus());
18224
18584
 
18225
- export { AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, BelongsToMany, BelongsToOne, Capability, CapabilityInput, ComputeLogEntry, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LocalModel, LocalModelInput, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RpcError as RestError, RpcError, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, determineNamespace, determinePredicate, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, ifExpr, invalidatePerspectiveCache, isArrayType, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, linkEqual, literal, normalizeNamespaceString, normalizeSchemaType, normalizeValue, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString };
18585
+ export { AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, AutoProcessorConfig, BelongsToMany, BelongsToOne, Capability, CapabilityInput, ComputeLogEntry, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, InterpretationOverlay, InterpretationRun, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LocalModel, LocalModelInput, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RpcError as RestError, RpcError, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, determineNamespace, determinePredicate, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, ifExpr, invalidatePerspectiveCache, isArrayType, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, linkEqual, literal, normalizeNamespaceString, normalizeSchemaType, normalizeValue, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString };
@@ -77,7 +77,9 @@ export class AIClient {
77
77
  async embed(modelId, text) {
78
78
  const aiEmbed = await __classPrivateFieldGet(this, _AIClient_apiClient, "f").call('ai.embed', { modelId, text });
79
79
  const compressed = base64js.toByteArray(aiEmbed);
80
- const decompressed = JSON.parse(pako.inflate(compressed, { to: 'string' }));
80
+ // Decode to a string via TextDecoder rather than pako's `{ to: 'string' }`
81
+ // option: newer @types/pako dropped that overload, which broke the build.
82
+ const decompressed = JSON.parse(new TextDecoder().decode(pako.inflate(compressed)));
81
83
  return decompressed;
82
84
  }
83
85
  async openTranscriptionStream(modelId, streamCallback, params) {
@@ -42,9 +42,12 @@ export declare class ApiClient {
42
42
  * Send an RPC call over the WebSocket connection.
43
43
  * @param type - The operation type (e.g. 'agent.get', 'perspective.all')
44
44
  * @param params - Optional parameters to include in the message
45
+ * @param timeoutMs - Optional per-call timeout override in ms. Defaults to
46
+ * [[DEFAULT_TIMEOUT_MS]]. Use for long-running calls (LLM prompts,
47
+ * holochain ops) that legitimately exceed the default.
45
48
  * @returns Promise that resolves with the result from the server
46
49
  */
47
- call<T>(type: string, params?: Record<string, unknown>): Promise<T>;
50
+ call<T>(type: string, params?: Record<string, unknown>, timeoutMs?: number): Promise<T>;
48
51
  subscribe<T = WsEvent>(callback: (data: T) => void): () => void;
49
52
  /** Wait until the WebSocket connection is established. */
50
53
  waitForSubscription(): Promise<void>;
@@ -163,20 +163,24 @@ export class ApiClient {
163
163
  * Send an RPC call over the WebSocket connection.
164
164
  * @param type - The operation type (e.g. 'agent.get', 'perspective.all')
165
165
  * @param params - Optional parameters to include in the message
166
+ * @param timeoutMs - Optional per-call timeout override in ms. Defaults to
167
+ * [[DEFAULT_TIMEOUT_MS]]. Use for long-running calls (LLM prompts,
168
+ * holochain ops) that legitimately exceed the default.
166
169
  * @returns Promise that resolves with the result from the server
167
170
  */
168
- async call(type, params) {
171
+ async call(type, params, timeoutMs) {
169
172
  await this._ready();
170
173
  const id = nextId();
171
174
  // Put params under a "params" key to avoid collision with
172
175
  // protocol fields "id" and "type" (e.g. params might contain
173
176
  // { id: modelId } or { type: "db" }).
174
177
  const message = { id, type, params: params || {} };
178
+ const effectiveTimeout = timeoutMs ?? DEFAULT_TIMEOUT_MS;
175
179
  return new Promise((resolve, reject) => {
176
180
  const timer = setTimeout(() => {
177
181
  this._pendingCalls.delete(id);
178
- reject(new RpcError(408, `RPC call '${type}' timed out after ${DEFAULT_TIMEOUT_MS}ms`));
179
- }, DEFAULT_TIMEOUT_MS);
182
+ reject(new RpcError(408, `RPC call '${type}' timed out after ${effectiveTimeout}ms`));
183
+ }, effectiveTimeout);
180
184
  this._pendingCalls.set(id, {
181
185
  resolve: resolve,
182
186
  reject,
@@ -0,0 +1,19 @@
1
+ import type { TranscriptTurn } from "./TranscriptTurn";
2
+ /**
3
+ * Run generic LLM interpretation over a transcript into the perspective's own
4
+ * SHACL subject classes. Shapes are resolved server-side from the
5
+ * perspective's registered classes, so callers pass only the transcript.
6
+ */
7
+ export type RunInterpretationRequest = {
8
+ uuid: string;
9
+ transcript: Array<TranscriptTurn>;
10
+ /**
11
+ * URI namespace new instance identities are minted under, e.g. `soa://ext/`.
12
+ */
13
+ basePrefix: string;
14
+ /**
15
+ * Local names of the subject classes to extract into (e.g. `["Task","Belief"]`).
16
+ * `None`/empty selects all subject classes registered in the perspective.
17
+ */
18
+ classes: Array<string> | null;
19
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,7 @@
1
+ /**
2
+ * One conversation turn fed to the extractor.
3
+ */
4
+ export type TranscriptTurn = {
5
+ speaker: string;
6
+ text: string;
7
+ };
@@ -0,0 +1,2 @@
1
+ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
+ export {};
@@ -29,11 +29,13 @@ export type { PublishNeighbourhoodRequest } from "./PublishNeighbourhoodRequest"
29
29
  export type { QueryRequest } from "./QueryRequest";
30
30
  export type { RemoveLinkRequest } from "./RemoveLinkRequest";
31
31
  export type { RemoveLinksBulkRequest } from "./RemoveLinksBulkRequest";
32
+ export type { RunInterpretationRequest } from "./RunInterpretationRequest";
32
33
  export type { SetDefaultModelRequest } from "./SetDefaultModelRequest";
33
34
  export type { SetFreeHostingEnabledRequest } from "./SetFreeHostingEnabledRequest";
34
35
  export type { SetMultiUserRequest } from "./SetMultiUserRequest";
35
36
  export type { SetStatusRequest } from "./SetStatusRequest";
36
37
  export type { SignMessageRequest } from "./SignMessageRequest";
38
+ export type { TranscriptTurn } from "./TranscriptTurn";
37
39
  export type { TrustedAgentsRequest } from "./TrustedAgentsRequest";
38
40
  export type { UnlockAgentRequest } from "./UnlockAgentRequest";
39
41
  export type { UpdateLinkRequest } from "./UpdateLinkRequest";
@@ -16,6 +16,8 @@ export * from "./Literal";
16
16
  export * from "./perspectives/Perspective";
17
17
  export * from "./perspectives/PerspectiveHandle";
18
18
  export * from "./perspectives/PerspectiveProxy";
19
+ export * from "./perspectives/AutoProcessor";
20
+ export * from "./perspectives/InterpretationModels";
19
21
  export * from "./perspectives/SparqlBindings";
20
22
  export * from "./perspectives/WakerSubscriptionManager";
21
23
  export * from "./perspectives/PerspectiveDiff";