hyperspace-sdk-ts 3.1.1 → 3.1.3

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # HyperspaceDB TypeScript SDK
2
2
 
3
- Official TypeScript client for HyperspaceDB gRPC API v3.1.0.
3
+ Official TypeScript client for HyperspaceDB gRPC API v3.1.1.
4
4
 
5
5
  Use this SDK for:
6
6
  - collection lifecycle management
@@ -8,8 +8,14 @@ Use this SDK for:
8
8
  - high-throughput batched search (`searchBatch`)
9
9
  - bulk insertion (`batchInsert`)
10
10
  - advanced filtering and hybrid search
11
+ - recursive logical filters (`AND`, `OR`, `NOT`)
12
+ - bulk point retrieval (`getPoints`)
13
+ - metadata updates (`updatePayload`)
14
+ - paginated scanning (`scroll`)
15
+ - filtered point counting (`count`)
16
+ - health monitoring (`healthCheck`)
11
17
  - typed metadata (`string | number | boolean`)
12
- - graph traversal APIs (`getNode`, `getNeighbors`, `getConceptParents`, `traverse`, `findSemanticClusters`)
18
+ - graph traversal APIs (`getNode`, `getNeighbors`, `getSubsumptionTree`, `getConceptParents`, `traverse`, `exploreGraph`, `findSemanticClusters`)
13
19
  - rebuild with metadata pruning (`rebuildIndexWithFilter`)
14
20
  - multi-tenant authentication headers (`x-api-key`, `x-hyperspace-user-id`)
15
21
 
@@ -34,7 +40,12 @@ async function main() {
34
40
  const collection = "docs_ts";
35
41
 
36
42
  await client.deleteCollection(collection).catch(() => {});
37
- await client.createCollection(collection, 3, "cosine");
43
+ await client.createCollection(collection, {
44
+ components: [
45
+ { name: "primary", metric: "cosine", full_dimension: 3, weight: 1.0 }
46
+ ],
47
+ cascade_pipeline: []
48
+ });
38
49
 
39
50
  await client.insert(1, [0.1, 0.2, 0.3], { source: "demo" }, collection);
40
51
  await client.insert(2, [0.2, 0.1, 0.4], { source: "demo" }, collection);
@@ -59,11 +70,22 @@ main().catch(console.error);
59
70
  - `apiKey`: optional API key
60
71
  - `userId`: optional tenant/user ID
61
72
 
62
- ### `createCollection(name, dimension, metric)`
73
+ ### `createCollection(name, schema)`
63
74
 
64
- Create a new collection.
75
+ Create a new collection using a `CollectionSchema`.
65
76
 
66
- - `metric`: `"l2" | "cosine" | "poincare" | "lorentz"`
77
+ - `metric`: `"l2" | "cosine" | "poincare" | "lorentz" | "hybrid"`
78
+
79
+ ```ts
80
+ await client.createCollection("my_coll", {
81
+ components: [
82
+ { name: "primary", metric: "lorentz", full_dimension: 129, weight: 1.0 }
83
+ ],
84
+ cascade_pipeline: [
85
+ { component_name: "primary", cutoff_dimension: 17, store_in_ram: true, rerank_top_k: 100 }
86
+ ]
87
+ });
88
+ ```
67
89
 
68
90
  ### `deleteCollection(name)`
69
91
 
@@ -77,7 +99,7 @@ Returns `Promise<CollectionInfo[]>`.
77
99
  ```ts
78
100
  const collections = await client.listCollections();
79
101
  for (const col of collections) {
80
- console.log(`${col.name}: dim=${col.dimension}, metric=${col.metric}, count=${col.count}`);
102
+ console.log(`${col.name}: count=${col.count}, schema=${JSON.stringify(col.schema)}`);
81
103
  }
82
104
  ```
83
105
 
@@ -122,9 +144,9 @@ const results = await client.searchText("How to use HyperspaceDB?", 10, "coll",
122
144
  });
123
145
  ```
124
146
 
125
- ### Geometric Filters (New in v3.0)
147
+ ### Geometric Filters
126
148
 
127
- HyperspaceDB v3.0 introduces advanced spatial filters that run on the engine level:
149
+ HyperspaceDB introduces advanced spatial filters that run on the engine level:
128
150
 
129
151
  ```ts
130
152
  // 1. Proximity Search (Ball)
@@ -145,8 +167,50 @@ const coneFilter = {
145
167
  const results = await client.search([0.1, 0.2, 0.3], 10, "coll", {
146
168
  filters: [ballFilter, boxFilter]
147
169
  });
170
+
171
+ // 4. Recursive Logical Filters
172
+ const logicFilter = {
173
+ and: [
174
+ { match: { key: "status", value: "active" } },
175
+ { or: [
176
+ { range: { key: "score", gte: 0.8 } },
177
+ { match: { key: "priority", value: "high" } }
178
+ ]
179
+ }
180
+ ]
181
+ };
182
+ ```
183
+
184
+ ### `getPoints(ids, collection?)`
185
+
186
+ Retrieve multiple points by their IDs.
187
+ Returns `Promise<Point[]>`.
188
+
189
+ ### `updatePayload(id, metadata, collection?)`
190
+
191
+ Patch metadata for an existing point.
192
+ ```ts
193
+ await client.updatePayload(1, { status: "processed", tags: "updated" });
148
194
  ```
149
195
 
196
+ ### `scroll(limit?, offset?, filters?, collection?)`
197
+
198
+ Paginated retrieval of points with optional filtering.
199
+ ```ts
200
+ const points = await client.scroll(50, 0, [{ match: { key: "category", value: "news" } }]);
201
+ ```
202
+
203
+ ### `count(filters?, collection?)`
204
+
205
+ Count points matching filters.
206
+ ```ts
207
+ const total = await client.count([{ range: { key: "price", lte: 100 } }]);
208
+ ```
209
+
210
+ ### `healthCheck()`
211
+
212
+ Check server connectivity. Returns `"ONLINE"` or throws.
213
+
150
214
  ### Hybrid & Lexical Search (BM25)
151
215
 
152
216
  HyperspaceDB supports combined lexical and vector ranking.
@@ -244,21 +308,47 @@ Provides advanced tools for Agentic AI, running entirely on the client side:
244
308
  import { CognitiveMath } from "hyperspace-sdk-ts";
245
309
 
246
310
  // 1. Detect Hallucinations (Entropy approaches 1.0)
247
- const entropy = CognitiveMath.localEntropy(candidateThought, neighbors, 1.0);
311
+ const entropy = client.localEntropy(candidateThought, neighbors, 1.0);
248
312
 
249
313
  // 2. Proof of Convergence (Negative derivative = convergence)
250
- const stability = CognitiveMath.lyapunovConvergence(chainOfThought, 1.0);
314
+ const stability = await client.getTrustScore([1, 2, 3]);
251
315
 
252
316
  // 3. Extrapolate next thought (Koopman linearization)
253
- const nextThought = CognitiveMath.koopmanExtrapolate(past, current, 1.0, 1.0);
317
+ const nextThought = await client.predictMomentum([10, 11], 1.0);
254
318
 
255
319
  // 4. Phase-Locked Loop for topic tracking
256
320
  const syncedThought = CognitiveMath.contextResonance(thought, globalContext, 0.5, 1.0);
321
+
322
+ // 5. Predict Semantic Relation (A + R ≈ B)
323
+ const relation = await client.predictRelation(1, 2);
324
+ ```
325
+
326
+ ## Implicit Graph Engine (v3.1.1)
327
+
328
+ HyperspaceDB treats your vectors as nodes in a dynamic graph. Relationships are inferred from the geometry:
329
+ - **Lorentz / Poincare**: Hierarchy and subsumption (light cones).
330
+ - **L2 / Cosine**: Semantic similarity and adjacency.
331
+
332
+ ### Subsumption Trees
333
+ Extract directed hierarchies from Lorentz-encoded data:
334
+ ```ts
335
+ const tree = await client.getSubsumptionTree(1, 5);
336
+ ```
337
+
338
+ ### Advanced Traversal
339
+ Navigate the graph using physical kernels:
340
+ ```ts
341
+ const results = await client.traverse({
342
+ startId: 1,
343
+ traversalMode: 2, // 0: GREEDY, 1: DIFFUSIVE, 2: MOMENTUM
344
+ breadthLimit: 5
345
+ });
346
+ ```
257
347
  ```
258
348
 
259
349
  ## Embedding Pipeline (Optional)
260
350
 
261
- HyperspaceDB supports **per-geometry embeddings** — each geometry (`l2`, `cosine`, `poincare`, `lorentz`) can have its own backend independently.
351
+ HyperspaceDB supports **per-geometry embeddings** — each geometry (`l2`, `cosine`, `poincare`, `lorentz`, `hybrid`) can have its own backend independently.
262
352
 
263
353
  ### Server-Side Config (`.env`)
264
354
 
@@ -330,3 +420,58 @@ const vector = await embedder.encode("my text");
330
420
  All methods reject on transport/protocol errors. Targets gRPC data plane operations.
331
421
  For control plane endpoints (`/api/*`), use regular HTTP requests to the server's HTTP port.
332
422
 
423
+ ## Zero-Knowledge Client-Side Encryption (ZK-Privacy)
424
+
425
+ HyperspaceDB v3.1.1 introduces Zero-Knowledge client-side encryption (ZK-Privacy). All private data (vectors, metadata, payloads) are encrypted/obfuscated *before* they leave the client. The database server never sees the raw vectors or plaintext data, ensuring maximum security even in public or untrusted DePIN environments.
426
+
427
+ ### Key Features
428
+ 1. **Vector Projection**: High-dimensional vectors are projected using a deterministic orthogonal matrix (or Lorentz boost matrix for hyperbolic spaces) generated from the collection key. This preserves distances (L2, Cosine, Lorentz) while hiding the vector coordinates.
429
+ 2. **Anisotropic Noise Injection**: Injecting subtle deterministic noise into the vectors to prevent reconstruction attacks.
430
+ 3. **Payload Encryption**: Sidecar payloads are encrypted client-side using AES-256-GCM before being sent to the database.
431
+ 4. **Metadata Hashing**: Metadata keys and values are obfuscated using HMAC-SHA256.
432
+
433
+ ### Usage Example
434
+
435
+ ```ts
436
+ import { HyperspaceClient } from "hyperspace-sdk-ts";
437
+
438
+ async function main() {
439
+ const client = new HyperspaceClient("localhost:50051", "I_LOVE_HYPERSPACEDB");
440
+
441
+ const collection = "encrypted_docs";
442
+ const secretKey = "my-super-secret-key";
443
+
444
+ // Register collection key to enable automatic client-side encryption/decryption
445
+ // noiseSigma defaults to 0.02 (2% anisotropic noise)
446
+ client.registerCollectionKey(collection, secretKey, "cosine", 0.02);
447
+
448
+ // 1. Insert vector (will be projected, noise injected, payload encrypted, metadata hashed)
449
+ await client.insert(
450
+ 1,
451
+ [0.1, 0.2, 0.3],
452
+ { category: "confidential" },
453
+ collection,
454
+ undefined,
455
+ undefined,
456
+ Buffer.from("This is a highly secret document payload", "utf-8")
457
+ );
458
+
459
+ // 2. Search (search vector is projected and noise-injected; results are decrypted locally)
460
+ const results = await client.search([0.1, 0.2, 0.3], 5, collection, {
461
+ // Filters are automatically hashed client-side
462
+ filter: { category: "confidential" }
463
+ });
464
+
465
+ for (const res of results) {
466
+ console.log(`ID: ${res.id}, Distance: ${res.distance}`);
467
+ if (res.payload) {
468
+ console.log(`Decrypted Payload: ${Buffer.from(res.payload).toString("utf-8")}`);
469
+ }
470
+ }
471
+
472
+ client.close();
473
+ }
474
+
475
+ main().catch(console.error);
476
+ ```
477
+
package/dist/client.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as grpc from '@grpc/grpc-js';
2
2
  import { DurabilityLevel, EventMessage } from './proto/hyperspace_pb';
3
3
  import * as hyperspace_pb from './proto/hyperspace_pb';
4
- export * as CognitiveMath from './math';
4
+ export * as CognitiveMathExport from './math';
5
5
  export { TribunalContext } from './agents';
6
6
  export { DurabilityLevel };
7
7
  export type TypedMetadataValue = string | number | boolean;
@@ -10,11 +10,31 @@ export interface Filter {
10
10
  key: string;
11
11
  value: string;
12
12
  };
13
+ prefix?: {
14
+ key: string;
15
+ prefix: string;
16
+ };
13
17
  range?: {
14
18
  key: string;
15
19
  gte?: number;
16
20
  lte?: number;
17
21
  };
22
+ inCone?: {
23
+ axes: number[];
24
+ apertures: number[];
25
+ cen: number[];
26
+ };
27
+ inBall?: {
28
+ center: number[];
29
+ radius: number;
30
+ };
31
+ inBox?: {
32
+ minBounds: number[];
33
+ maxBounds: number[];
34
+ };
35
+ and?: Filter[];
36
+ or?: Filter[];
37
+ not?: Filter;
18
38
  }
19
39
  export interface SearchResult {
20
40
  id: number;
@@ -25,12 +45,51 @@ export interface SearchResult {
25
45
  typedMetadata: {
26
46
  [key: string]: TypedMetadataValue;
27
47
  };
48
+ payload?: Uint8Array;
49
+ }
50
+ export interface VectorComponent {
51
+ name: string;
52
+ metric: string;
53
+ fullDimension: number;
54
+ weight: number;
55
+ }
56
+ export interface MrlLayer {
57
+ componentName: string;
58
+ cutoffDimension: number;
59
+ storeInRam: boolean;
60
+ rerankTopK: number;
61
+ }
62
+ export interface CollectionSchema {
63
+ components: VectorComponent[];
64
+ cascadePipeline: MrlLayer[];
28
65
  }
29
66
  export interface CollectionInfo {
30
67
  name: string;
31
68
  count: number;
32
- dimension: number;
33
- metric: string;
69
+ schema?: CollectionSchema;
70
+ }
71
+ export interface CollectionStats {
72
+ count: number;
73
+ schema?: CollectionSchema;
74
+ indexingQueue: number;
75
+ diskUsageBytes: number;
76
+ ramUsageBytes: number;
77
+ activeTasks: number;
78
+ }
79
+ export interface SystemMetrics {
80
+ cpuUsage: number;
81
+ ramUsageMb: number;
82
+ totalVectors: number;
83
+ activeCollections: number;
84
+ uptimeSeconds: number;
85
+ networkRxBytes: number;
86
+ networkTxBytes: number;
87
+ }
88
+ export interface CollectionConfig {
89
+ quantizationMode?: 'NONE' | 'SCALAR_I8';
90
+ efSearch?: number;
91
+ efConstruction?: number;
92
+ m?: number;
34
93
  }
35
94
  export interface GraphNode {
36
95
  id: number;
@@ -78,19 +137,50 @@ export declare const HyperbolicMath: {
78
137
  export declare class HyperspaceClient {
79
138
  private client;
80
139
  private metadata;
140
+ private host;
141
+ private apiKey?;
142
+ private userId?;
143
+ embedder?: {
144
+ encode: (text: string) => Promise<number[]> | number[];
145
+ };
146
+ private collectionKeys;
147
+ private encryptionContexts;
148
+ private collectionMetrics;
149
+ private collectionNoiseSigmas;
150
+ private collectionSchemas;
81
151
  private static toVectorList;
82
152
  private static toProtoMetadataValue;
83
153
  private static parseTypedMetadata;
154
+ private toProtoFilter;
84
155
  constructor(host?: string, apiKey?: string, userId?: string);
85
- createCollection(name: string, dimension: number, metric: string): Promise<boolean>;
156
+ registerCollectionKey(collectionName: string, key: string, metric?: string, noiseSigma?: number, schema?: CollectionSchema): void;
157
+ private deriveKeys;
158
+ private encryptPayload;
159
+ private decryptPayload;
160
+ private hashMetadataKey;
161
+ private hashMetadataValue;
162
+ private _getEncryptionContext;
163
+ private _projectSingleBlock;
164
+ private _projectCollectionVector;
165
+ private _encryptFilters;
166
+ createCollection(name: string, schema: CollectionSchema, encryptionKey?: string, noiseSigma?: number): Promise<boolean>;
86
167
  deleteCollection(name: string): Promise<boolean>;
168
+ freezeCollection(name: string): Promise<string>;
169
+ unfreezeCollection(name: string): Promise<string>;
87
170
  listCollections(): Promise<CollectionInfo[]>;
171
+ getPoints(ids: number[], collection?: string): Promise<{
172
+ id: number;
173
+ vector: number[];
174
+ metadata: {
175
+ [key: string]: string;
176
+ };
177
+ }[]>;
88
178
  delete(id: number, collection?: string): Promise<boolean>;
89
179
  insert(id: number, vector: number[] | Float32Array | Float64Array, meta?: {
90
180
  [key: string]: string;
91
181
  }, collection?: string, durability?: DurabilityLevel, typedMetadata?: {
92
182
  [key: string]: TypedMetadataValue;
93
- }): Promise<boolean>;
183
+ }, payload?: Uint8Array): Promise<boolean>;
94
184
  insertText(id: number, text: string, meta?: {
95
185
  [key: string]: string;
96
186
  }, collection?: string, durability?: DurabilityLevel): Promise<boolean>;
@@ -106,15 +196,27 @@ export declare class HyperspaceClient {
106
196
  };
107
197
  }[], collection?: string, durability?: DurabilityLevel): Promise<boolean>;
108
198
  search(vector: number[] | Float32Array | Float64Array, topK: number, collection?: string, options?: {
199
+ filter?: {
200
+ [key: string]: string;
201
+ };
109
202
  filters?: Filter[];
110
203
  hybridQuery?: string;
111
204
  hybridAlpha?: number;
112
205
  bm25?: Bm25Options;
206
+ mrlDimension?: number;
207
+ useWasserstein?: boolean;
208
+ includePayload?: boolean;
209
+ componentWeights?: {
210
+ [key: string]: number;
211
+ };
212
+ useWave?: boolean;
213
+ restartFactor?: number;
113
214
  }): Promise<SearchResult[]>;
114
215
  searchText(text: string, topK: number, collection?: string, options?: {
115
216
  filters?: Filter[];
116
217
  bm25?: Bm25Options;
117
218
  hybridAlpha?: number;
219
+ includePayload?: boolean;
118
220
  }): Promise<SearchResult[]>;
119
221
  searchBatch(vectors: Array<number[] | Float32Array | Float64Array>, topK: number, collection?: string): Promise<SearchResult[][]>;
120
222
  getDigest(collection?: string): Promise<{
@@ -137,5 +239,20 @@ export declare class HyperspaceClient {
137
239
  subscribeToEvents(options: SubscribeOptions, onEvent: (event: EventMessage) => void, onError?: (err: Error) => void): grpc.ClientReadableStream<EventMessage>;
138
240
  syncHandshake(collection: string, clientBuckets: number[], clientLogicalClock?: number, clientCount?: number): Promise<hyperspace_pb.SyncHandshakeResponse.AsObject>;
139
241
  syncPull(collection: string, bucketIndices: number[], onData: (data: hyperspace_pb.SyncVectorData.AsObject) => void, onError?: (err: Error) => void): grpc.ClientReadableStream<hyperspace_pb.SyncVectorData>;
242
+ getCollectionStats(name: string): Promise<CollectionStats>;
243
+ exists(name: string): Promise<boolean>;
244
+ getCacheStats(name: string): Promise<any>;
245
+ clearCache(name: string): Promise<boolean>;
246
+ updateCacheConfig(name: string, policy: string, annThreshold?: number): Promise<boolean>;
247
+ updateCollection(name: string, config: CollectionConfig): Promise<boolean>;
248
+ createSnapshot(): Promise<boolean>;
249
+ vacuum(): Promise<boolean>;
250
+ getMetrics(onData: (data: any) => void, onError?: (err: Error) => void): grpc.ClientReadableStream<any>;
251
+ searchMultiCollection(collections: string[], query: number[]): Promise<any>;
252
+ triggerReconsolidation(collection: string, targetVector: number[], learningRate?: number): Promise<boolean>;
253
+ getSubsumptionTree(rootId: number, maxDepth?: number, collection?: string): Promise<GraphNode[]>;
254
+ exploreGraph(startId: number, maxDepth?: number, maxNodes?: number, collection?: string): Promise<any>;
255
+ predictMomentum(trajectoryIds: number[], steps?: number, collection?: string, curvature?: number): Promise<number[]>;
256
+ getTrustScore(trajectoryIds: number[], collection?: string, curvature?: number): Promise<number>;
140
257
  close(): void;
141
258
  }