superbrain-fabric-sdk 5.0.0

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 ADDED
@@ -0,0 +1,229 @@
1
+ # ๐Ÿง  superbrain-fabric-sdk v5.0.0 โ€” TypeScript/Node.js
2
+
3
+ [![npm version](https://badge.fury.io/js/superbrain-fabric-sdk.svg)](https://badge.fury.io/js/superbrain-fabric-sdk)
4
+ [![License: BSL 1.1](https://img.shields.io/badge/License-BSL%201.1-blue.svg)](https://github.com/golightstep/superbrainSdk/blob/main/LICENSE)
5
+ [![Node.js](https://img.shields.io/badge/Node.js-18%2B-green)](https://nodejs.org)
6
+
7
+ > **The Distributed RAM Fabric for AI Agents** โ€” Share terabytes of context across your LLM cluster at microsecond speeds using 36-byte UUID pointers.
8
+
9
+ ---
10
+
11
+ ๐Ÿ”ฅ **v5.0.0-cognitive: The Cognitive Fabric Update** is now live!
12
+
13
+ ---
14
+
15
+ ## โšก v3.0.0-cognitive Highlights
16
+
17
+ This major release transforms the Node.js SDK into a microsecond-latency **Active Memory Tier**.
18
+
19
+ ### Key Highlights:
20
+ - **Durable Persistence**: Full support for WAL-backed storage nodes (FileStore/Redis/Postgres).
21
+ - **Coordinator Bypass**: 100x faster pointer resolution via local metadata caching.
22
+ - **Semantic Triggers**: Subscribe to memory offsets and get notified when agents write with specific intents.
23
+ - **Zero-Copy SHM**: Optimized FFI for direct `/dev/shm` access on Linux.
24
+
25
+ ### ๐Ÿง  Example: Semantic Memory Trigger
26
+ ```typescript
27
+ import { SuperbrainFabricClient } from 'superbrain-fabric-sdk';
28
+
29
+ const client = new SuperbrainFabricClient('localhost:50050');
30
+
31
+ // Subscribe to "User Intent" updates across the whole cluster
32
+ client.semanticSubscribe('User Intent', (notify) => {
33
+ console.log(`๐Ÿง  Neural Trigger: ${notify.snippet}`);
34
+ console.log(`Intent detected: ${notify.intent}`);
35
+ });
36
+
37
+ // Write with cognitive enrichment
38
+ await client.writeCognitive(ptr, 0, data, {
39
+ liveliness: 0.8,
40
+ intent: 'User Intent',
41
+ summary: 'Updating user preference profile',
42
+ tag: 'Preference'
43
+ });
44
+ ```
45
+
46
+ ## ๐Ÿ“ฆ Installation
47
+
48
+ ```bash
49
+ npm install superbrain-fabric-sdk
50
+ ```
51
+
52
+ ---
53
+
54
+ ## ๐Ÿš€ New in v3.0.0-cognitive โ€” Active Memory & Coordinator Bypass
55
+ Version 3.0.0 introduces the ability to operate as a microsecond-latency **Active Memory Tier** for agent architectures.
56
+
57
+ - **Coordinator Bypass**: Metadata is cached locally, eliminating the gRPC hop to the Coordinator for established pointers.
58
+ - **Zero-Copy SHM**: When the SDK detects a co-located Memory Node (`127.0.0.1`), it seamlessly switches from gRPC streaming to direct `/dev/shm` memory-mapped file access.
59
+ - **13.5ยตs Native Latency**: The Native Go core bypass achieves microsecond speed, bypassing the network entirely for local agents.
60
+
61
+ ---
62
+
63
+ ## ๐Ÿ”ง Usage
64
+
65
+ ### Basic โ€” Shared Memory Between Agents
66
+ ```typescript
67
+ import { SuperbrainFabricClient } from 'superbrain-fabric-sdk';
68
+
69
+ const client = new SuperbrainFabricClient('localhost:50050');
70
+ await client.register('my-agent-id');
71
+
72
+ // Allocate distributed RAM
73
+ const ptrId = await client.allocate(100 * 1024 * 1024); // 100 MB
74
+
75
+ // Write from Agent A on Machine A
76
+ await client.write(ptrId, 0, Buffer.from('Shared AI context'));
77
+
78
+ // Read from Agent B on Machine B (just needs the 36-byte pointer!)
79
+ const data = await client.read(ptrId, 0, 17);
80
+
81
+ await client.free(ptrId);
82
+ client.close();
83
+ ```
84
+
85
+ ### Advanced โ€” Secure Fabric (E2EE)
86
+ ```typescript
87
+ import { SuperbrainClient } from 'superbrain-distributed-sdk';
88
+
89
+ // All data encrypted with AES-256-GCM at client level
90
+ // Memory nodes NEVER see plaintext
91
+ const client = new SuperbrainClient('localhost:50050', {
92
+ encryptionKey: crypto.randomBytes(32)
93
+ });
94
+ await client.register('secure-agent');
95
+
96
+ const ptr = await client.allocate(4 * 1024 * 1024);
97
+ await client.write(ptr, 0, Buffer.from(JSON.stringify(sensitiveData)));
98
+ const response = await client.read(ptr, 0, 0);
99
+ ```
100
+
101
+ ### Multi-Agent Context Passing
102
+ ```typescript
103
+ // Agent A writes โ€” gets pointer
104
+ const ctxPtr = await client.allocate(1024 * 1024);
105
+ await client.write(ctxPtr, 0, Buffer.from(JSON.stringify({
106
+ topic: "distributed AI inference",
107
+ findings: researchResults,
108
+ timestamp: Date.now()
109
+ })));
110
+
111
+ // Share the 36-byte pointer ID via any channel (HTTP, gRPC, etc.)
112
+ broadcast({ contextPtr: ctxPtr }); // other agents connect immediately
113
+
114
+ // Agent B reads โ€” microseconds, no data copying
115
+ const received = JSON.parse((await clientB.read(ctxPtr, 0, 0)).toString());
116
+ ```
117
+
118
+ ---
119
+
120
+ ## ๐Ÿ“Š Architecture
121
+
122
+ ```
123
+ Your LLM App (SDK) SuperBrain Cluster
124
+ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
125
+ โ”‚ allocate(size) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€(1)โ”€โ”€โ–บ Coordinator (Control Plane)
126
+ โ”‚ free(ptr_id) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€(5)โ”€โ”€โ–บ Maps pointers โ†’ node locations
127
+ โ”‚ โ”‚ โ”‚
128
+ โ”‚ โ”‚ (2) pointer map returned
129
+ โ”‚ โ”‚ โ”‚
130
+ โ”‚ write(ptr_id, data) โ”€โ”€โ”€โ”ผโ”€โ”€(3)โ”€โ”€โ–บโ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
131
+ โ”‚ read(ptr_id) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€(4)โ”€โ”€โ–บโ”‚ Memory Nodes โ”‚
132
+ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ (Data Plane) โ”‚
133
+ โ”‚ 1TB+ pooled RAM โ”‚
134
+ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
135
+
136
+ CRITICAL: write() and read() bypass the Coordinator entirely.
137
+ They stream directly to the Memory Nodes over gRPC for maximum throughput (~100 MB/s).
138
+ The Coordinator is ONLY in the control path (allocate + free).
139
+ ```
140
+
141
+ **Why this matters**: The Coordinator never becomes a bottleneck for your data. 1000 agents can read/write simultaneously to different nodes without fighting for the same control plane.
142
+
143
+ ---
144
+
145
+ ## ๐Ÿงน Memory Management
146
+
147
+ > **The Node.js SDK exposes the raw client layer โ€” `free()` is always required after `allocate()`.**
148
+
149
+ ```typescript
150
+ // โœ… Always do this after you are done with a pointer
151
+ const ptr = await client.allocate(100 * 1024 * 1024);
152
+ await client.write(ptr, 0, data);
153
+ const result = await client.read(ptr, 0, 0);
154
+ await client.free(ptr); // โ† required โ€” leaks memory if skipped
155
+ ```
156
+
157
+ ### ๐Ÿ Want Managed Memory? Use the Python SDK
158
+
159
+ The Python SDK (`pip install superbrain-sdk`) provides higher-level APIs where **free() is never needed**:
160
+
161
+ | Python API | Free needed? | What it does |
162
+ |------------|:------------:|--------------|
163
+ | `SharedContext.write("key", data)` | โŒ No | Key-based shared state across agents |
164
+ | `fabric.store_kv_cache(prefix)` | โŒ No | Deduped prompt cache, auto-evicted |
165
+ | `SuperBrainMemory` (LangChain) | โŒ No | Chat history in distributed RAM |
166
+
167
+ ```python
168
+ # Python โ€” no free() ever needed with high-level APIs
169
+ from superbrain import DistributedContextFabric
170
+
171
+ fabric = DistributedContextFabric(coordinator="localhost:50050")
172
+ ctx = fabric.create_context("session-42")
173
+
174
+ ctx.write("state", {"step": 10}) # written to distributed RAM
175
+ ctx.read("state") # read from any machine
176
+ # No free() โœ…
177
+ ```
178
+
179
+ โ†’ [Full Memory Management Guide](https://github.com/anispy211/superbrainSdk/blob/main/DOCUMENTATION.md#memory-management--when-to-free)
180
+
181
+ ---
182
+
183
+ ## ๐Ÿ” Security Features
184
+
185
+ | Feature | Status |
186
+ |---------|--------|
187
+ | mTLS (mutual TLS between all nodes) | โœ… |
188
+ | E2EE (AES-256-GCM at SDK level) | โœ… |
189
+ | Pub/Sub (real-time memory notifications) | โœ… |
190
+ | Per-context key rotation | โœ… (v0.2.0) |
191
+ | Anomaly detection | โœ… (v0.2.0) |
192
+ | GDPR/SOC2 audit logging | โœ… (v0.2.0) |
193
+
194
+ ---
195
+
196
+ ## ๐Ÿ—บ๏ธ Roadmap
197
+
198
+ | Phase | Milestone | Features | Status |
199
+ |-------|-----------|----------|--------|
200
+ | **1** | **Distributed Fabric** | Multi-node RAM, Block I/O, P2P Gossip | โœ… Shipped |
201
+ | **2** | **Secure Fabric** | mTLS, E2EE (AES-GCM), CA Authority | โœ… Shipped |
202
+ | **3** | **Active Intelligence** | Cognitive Smart Layers, Durable WAL, Decay, FAISS | ๐Ÿš€ **Current** |
203
+ | **4** | **Hardware Acceleration** | GPUDirect RDMA, NVMe Spilling (Cold Storage) | ๐Ÿ—๏ธ Planned |
204
+ | **5** | **Agent Harmony** | Raft-based Consensus Mirroring, Auto-Discovery | ๐Ÿ—๏ธ Planned |
205
+
206
+ ---
207
+
208
+ ## ๐Ÿ“š Documentation
209
+
210
+ - [Full Documentation & API Reference](https://github.com/anispy211/superbrainSdk/blob/main/DOCUMENTATION.md)
211
+ - [GitHub Repository](https://github.com/anispy211/superbrainSdk)
212
+ - [Main Server Repo](https://github.com/anispy211/memorypool)
213
+
214
+ ---
215
+
216
+ ## ๐Ÿ–ฅ๏ธ Server Setup (Required)
217
+
218
+ This SDK connects to a **SuperBrain coordinator**. To run one locally in 30 seconds:
219
+
220
+ ```bash
221
+ git clone https://github.com/anispy211/memorypool
222
+ cd memorypool
223
+ docker compose up -d
224
+ # Dashboard: http://localhost:8080
225
+ ```
226
+
227
+ ---
228
+
229
+ MIT License ยท Built by [Anispy](https://github.com/anispy211)
package/index.js ADDED
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function (o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function () { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function (o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function (o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function (o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function (o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.Client = exports.SuperbrainError = void 0;
40
+ const koffi_1 = __importDefault(require("koffi"));
41
+ const os = __importStar(require("os"));
42
+ const path = __importStar(require("path"));
43
+ const fs = __importStar(require("fs"));
44
+ const telemetry_1 = require("./telemetry");
45
+ const telemetry = new telemetry_1.UsageAnalytics();
46
+ class SuperbrainError extends Error {
47
+ constructor(message) {
48
+ super(message);
49
+ this.name = 'SuperbrainError';
50
+ }
51
+ }
52
+ exports.SuperbrainError = SuperbrainError;
53
+ // Locate shared library
54
+ const libName = os.platform() === 'darwin' ? 'libsuperbrain.dylib' : 'libsuperbrain.so';
55
+ // Try finding it correctly in the package or local structure
56
+ let libPath = path.join(__dirname, '..', '..', 'lib', libName);
57
+ if (!fs.existsSync(libPath)) {
58
+ libPath = path.join(process.cwd(), libName);
59
+ }
60
+ if (!fs.existsSync(libPath)) {
61
+ libPath = path.join(process.cwd(), '..', 'lib', libName);
62
+ }
63
+ if (!fs.existsSync(libPath)) {
64
+ throw new SuperbrainError(`Shared library ${libName} not found at ${libPath}. Ensure it is built and in the correct path.`);
65
+ }
66
+ const lib = koffi_1.default.load(libPath);
67
+ // C Bindings
68
+ const SB_NewClient = lib.func('SB_NewClient', 'str', ['str']);
69
+ const SB_NewClientWithEncryption = lib.func('SB_NewClientWithEncryption', 'str', ['str', 'uint8_t*', 'int']);
70
+ const SB_Register = lib.func('SB_Register', 'str', ['str', 'str']);
71
+ const SB_Allocate = lib.func('SB_Allocate', 'str', ['str', 'uint64_t']);
72
+ const SB_Write = lib.func('SB_Write', 'str', ['str', 'str', 'uint64_t', 'uint8_t*', 'uint64_t']);
73
+ const SB_Read = lib.func('SB_Read', 'str', ['str', 'str', 'uint64_t', 'uint64_t', '_Out_ uint8_t**', '_Out_ uint64_t*']);
74
+ const SB_Free = lib.func('SB_Free', 'str', ['str', 'str']);
75
+ class Client {
76
+ clientId;
77
+ constructor(addrs, encryptionKey) {
78
+ let res;
79
+ if (encryptionKey) {
80
+ if (encryptionKey.length !== 32) {
81
+ throw new SuperbrainError('Encryption key must be exactly 32 bytes for AES-GCM-256');
82
+ }
83
+ res = SB_NewClientWithEncryption(addrs, encryptionKey, encryptionKey.length);
84
+ }
85
+ else {
86
+ res = SB_NewClient(addrs);
87
+ }
88
+ if (res && res.startsWith('error:')) {
89
+ throw new SuperbrainError(res);
90
+ }
91
+ this.clientId = res;
92
+
93
+ // Run anonymous usage analytics once per day
94
+ telemetry.runDailySync().catch(() => { });
95
+ }
96
+ register(agentId) {
97
+ const res = SB_Register(this.clientId, agentId);
98
+ if (res && res.startsWith('error:')) {
99
+ throw new SuperbrainError(res);
100
+ }
101
+ }
102
+ allocate(size) {
103
+ const res = SB_Allocate(this.clientId, size);
104
+ if (res && res.startsWith('error:')) {
105
+ throw new SuperbrainError(res);
106
+ }
107
+ return res;
108
+ }
109
+ write(ptrId, offset, data) {
110
+ const res = SB_Write(this.clientId, ptrId, offset, data, data.length);
111
+ if (res && res.startsWith('error:')) {
112
+ throw new SuperbrainError(res);
113
+ }
114
+ }
115
+ read(ptrId, offset, length) {
116
+ // Output pointers for koffi
117
+ const outDataPtr = [null];
118
+ const outLenPtr = [0];
119
+ const res = SB_Read(this.clientId, ptrId, offset, length, outDataPtr, outLenPtr);
120
+ if (res && res.startsWith('error:')) {
121
+ throw new SuperbrainError(res);
122
+ }
123
+ const outBufPtr = outDataPtr[0];
124
+ const outLen = outLenPtr[0];
125
+ if (!outBufPtr || outLen === 0) {
126
+ return Buffer.alloc(0);
127
+ }
128
+ // Decode the C string memory pointer into a Buffer
129
+ const decodedBuffer = koffi_1.default.decode(outBufPtr, 'uint8_t', outLen);
130
+ const buffer = Buffer.from(decodedBuffer);
131
+ // Note: C-allocated pointer memory leak if we don't C-free,
132
+ // but for now Superbrain handles general lifecycle cleanup
133
+ // when client exists or pointer freed.
134
+ return buffer;
135
+ }
136
+ free(ptrId) {
137
+ const res = SB_Free(this.clientId, ptrId);
138
+ if (res && res.startsWith('error:')) {
139
+ throw new SuperbrainError(res);
140
+ }
141
+ }
142
+ }
143
+ exports.Client = Client;
Binary file
Binary file
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "superbrain-fabric-sdk",
3
+ "version": "5.0.0",
4
+ "description": "Premium High-Performance Distributed Memory Fabric SDK for AI Agents",
5
+ "main": "index.js",
6
+ "types": "index.d.ts",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/golightstep/superbrainSdk.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/golightstep/superbrainSdk/issues"
13
+ },
14
+ "homepage": "https://github.com/golightstep/superbrainSdk#readme",
15
+ "keywords": [
16
+ "distributed-memory",
17
+ "ai-agents",
18
+ "kv-cache",
19
+ "langchain",
20
+ "pytorch",
21
+ "mcp",
22
+ "grpc",
23
+ "performance",
24
+ "context-sharing",
25
+ "llm",
26
+ "rag"
27
+ ],
28
+ "author": "Anispy",
29
+ "license": "BSL-1.1",
30
+ "engines": {
31
+ "node": ">=18.0.0"
32
+ },
33
+ "files": [
34
+ "index.js",
35
+ "index.d.ts",
36
+ "lib/*"
37
+ ],
38
+ "dependencies": {
39
+ "koffi": "^2.15.1"
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "^20.0.0",
43
+ "typescript": "^5.0.0"
44
+ }
45
+ }