mycai 1.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/LICENSE +23 -0
- package/README.md +119 -0
- package/bin/mycai.js +156 -0
- package/core/ghr_lattice_memory.js +401 -0
- package/core/hdc.js +312 -0
- package/core/memory.js +60 -0
- package/core/memory_engine.js +444 -0
- package/core/morphology.js +357 -0
- package/core/phase.js +87 -0
- package/core/reasoning_router.js +628 -0
- package/core/resonance.js +118 -0
- package/core/safetensors.js +62 -0
- package/core/sovereign_agent.js +164 -0
- package/core/spectral.js +259 -0
- package/core/spectral_decoder.js +868 -0
- package/dist/resonance_sdk.js +2703 -0
- package/dist/resonance_sdk.min.js +14 -0
- package/dist/spectral_core.wasm +0 -0
- package/index.d.ts +45 -0
- package/index.js +26 -0
- package/package.json +52 -0
- package/sdk/README.md +154 -0
- package/sdk/examples/banking_assistant.js +61 -0
- package/sdk/examples/browser_example.html +104 -0
- package/sdk/examples/express_integration.js +61 -0
- package/sdk/examples/node_example.js +33 -0
- package/sdk/examples/quickstart.js +55 -0
- package/sdk/index.js +22 -0
- package/sdk/ingestion.js +237 -0
- package/sdk/licensing.js +168 -0
- package/sdk/resonance_engine.js +594 -0
- package/sdk/resonance_sdk.js +792 -0
- package/sdk/storage.js +185 -0
- package/sdk/tests/sdk_verification.js +98 -0
- package/sdk/tests/test_commercial_sdk.js +136 -0
- package/sdk/types.d.ts +152 -0
package/sdk/storage.js
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resonance SDK - Storage Adapter Interface & Implementations
|
|
3
|
+
* Pluggable persistence layer for living memory nodes and telemetry across runtimes.
|
|
4
|
+
*
|
|
5
|
+
* @license Commercial
|
|
6
|
+
* @author Turkish Resonance AI Core Team
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import fs from 'fs';
|
|
10
|
+
import path from 'path';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Base abstract storage adapter
|
|
14
|
+
*/
|
|
15
|
+
export class BaseStorageAdapter {
|
|
16
|
+
constructor(name = 'default') {
|
|
17
|
+
this.name = name;
|
|
18
|
+
}
|
|
19
|
+
async init() {}
|
|
20
|
+
async load() { return []; }
|
|
21
|
+
async save(records) { return true; }
|
|
22
|
+
async clear() { return true; }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* In-Memory RAM Storage Adapter (Ultra-fast, zero disk dependency, default)
|
|
27
|
+
*/
|
|
28
|
+
export class MemoryStorageAdapter extends BaseStorageAdapter {
|
|
29
|
+
constructor() {
|
|
30
|
+
super('memory');
|
|
31
|
+
this._records = [];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async load() {
|
|
35
|
+
return [...this._records];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async save(records) {
|
|
39
|
+
this._records = Array.isArray(records) ? [...records] : [];
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async clear() {
|
|
44
|
+
this._records = [];
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Node.js Local File Storage Adapter (Persists memory snapshots to disk)
|
|
51
|
+
*/
|
|
52
|
+
export class FileStorageAdapter extends BaseStorageAdapter {
|
|
53
|
+
/**
|
|
54
|
+
* @param {string} filePath - Path to JSON persistence file
|
|
55
|
+
*/
|
|
56
|
+
constructor(filePath = './resonance_memory.json') {
|
|
57
|
+
super('file');
|
|
58
|
+
this.filePath = path.resolve(filePath);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async init() {
|
|
62
|
+
const dir = path.dirname(this.filePath);
|
|
63
|
+
if (!fs.existsSync(dir)) {
|
|
64
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async load() {
|
|
69
|
+
try {
|
|
70
|
+
if (!fs.existsSync(this.filePath)) return [];
|
|
71
|
+
const content = fs.readFileSync(this.filePath, 'utf8');
|
|
72
|
+
const data = JSON.parse(content);
|
|
73
|
+
return Array.isArray(data) ? data : [];
|
|
74
|
+
} catch (e) {
|
|
75
|
+
console.warn(`[Resonance Storage] Failed to load from ${this.filePath}:`, e.message);
|
|
76
|
+
return [];
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async save(records) {
|
|
81
|
+
try {
|
|
82
|
+
await this.init();
|
|
83
|
+
fs.writeFileSync(this.filePath, JSON.stringify(records, null, 2), 'utf8');
|
|
84
|
+
return true;
|
|
85
|
+
} catch (e) {
|
|
86
|
+
console.error(`[Resonance Storage] Failed to save to ${this.filePath}:`, e.message);
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async clear() {
|
|
92
|
+
try {
|
|
93
|
+
if (fs.existsSync(this.filePath)) {
|
|
94
|
+
fs.unlinkSync(this.filePath);
|
|
95
|
+
}
|
|
96
|
+
return true;
|
|
97
|
+
} catch (e) {
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Browser / Electron IndexedDB Storage Adapter
|
|
105
|
+
*/
|
|
106
|
+
export class IndexedDBStorageAdapter extends BaseStorageAdapter {
|
|
107
|
+
constructor(dbName = 'ResonanceMemoryDB', storeName = 'nodes') {
|
|
108
|
+
super('indexeddb');
|
|
109
|
+
this.dbName = dbName;
|
|
110
|
+
this.storeName = storeName;
|
|
111
|
+
this._db = null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async init() {
|
|
115
|
+
if (typeof indexedDB === 'undefined') {
|
|
116
|
+
return; // Fallback to memory if indexedDB not in environment
|
|
117
|
+
}
|
|
118
|
+
return new Promise((resolve, reject) => {
|
|
119
|
+
const req = indexedDB.open(this.dbName, 1);
|
|
120
|
+
req.onupgradeneeded = (e) => {
|
|
121
|
+
const db = e.target.result;
|
|
122
|
+
if (!db.objectStoreNames.contains(this.storeName)) {
|
|
123
|
+
db.createObjectStore(this.storeName, { keyPath: 'id', autoIncrement: true });
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
req.onsuccess = () => {
|
|
127
|
+
this._db = req.result;
|
|
128
|
+
resolve();
|
|
129
|
+
};
|
|
130
|
+
req.onerror = () => reject(req.error);
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async load() {
|
|
135
|
+
if (!this._db) await this.init();
|
|
136
|
+
if (!this._db) return [];
|
|
137
|
+
|
|
138
|
+
return new Promise((resolve) => {
|
|
139
|
+
try {
|
|
140
|
+
const tx = this._db.transaction(this.storeName, 'readonly');
|
|
141
|
+
const store = tx.objectStore(this.storeName);
|
|
142
|
+
const req = store.getAll();
|
|
143
|
+
req.onsuccess = () => resolve(req.result || []);
|
|
144
|
+
req.onerror = () => resolve([]);
|
|
145
|
+
} catch (e) {
|
|
146
|
+
resolve([]);
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async save(records) {
|
|
152
|
+
if (!this._db) await this.init();
|
|
153
|
+
if (!this._db) return false;
|
|
154
|
+
|
|
155
|
+
return new Promise((resolve) => {
|
|
156
|
+
try {
|
|
157
|
+
const tx = this._db.transaction(this.storeName, 'readwrite');
|
|
158
|
+
const store = tx.objectStore(this.storeName);
|
|
159
|
+
store.clear();
|
|
160
|
+
(records || []).forEach(r => store.add(r));
|
|
161
|
+
tx.oncomplete = () => resolve(true);
|
|
162
|
+
tx.onerror = () => resolve(false);
|
|
163
|
+
} catch (e) {
|
|
164
|
+
resolve(false);
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async clear() {
|
|
170
|
+
if (!this._db) await this.init();
|
|
171
|
+
if (!this._db) return true;
|
|
172
|
+
|
|
173
|
+
return new Promise((resolve) => {
|
|
174
|
+
try {
|
|
175
|
+
const tx = this._db.transaction(this.storeName, 'readwrite');
|
|
176
|
+
const store = tx.objectStore(this.storeName);
|
|
177
|
+
store.clear();
|
|
178
|
+
tx.oncomplete = () => resolve(true);
|
|
179
|
+
tx.onerror = () => resolve(false);
|
|
180
|
+
} catch (e) {
|
|
181
|
+
resolve(false);
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resonance SDK v1.0 - SDK Verification Suite
|
|
3
|
+
* Asserts: zero-copy WASM interface, memory limits, OOV correctness, and generation consistency.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { ResonanceSDK } from '../resonance_sdk.js';
|
|
7
|
+
|
|
8
|
+
let passed = 0, failed = 0, total = 0;
|
|
9
|
+
|
|
10
|
+
function assert(name, condition, detail = '') {
|
|
11
|
+
total++;
|
|
12
|
+
if (condition) {
|
|
13
|
+
passed++;
|
|
14
|
+
console.log(` ✅ ${name}`);
|
|
15
|
+
} else {
|
|
16
|
+
failed++;
|
|
17
|
+
console.log(` ❌ ${name} ${detail}`);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function runTests() {
|
|
22
|
+
console.log('\n╔══════════════════════════════════════════════════════════╗');
|
|
23
|
+
console.log('║ RESONANCE SDK v1.0 — SPEC VERIFICATION ║');
|
|
24
|
+
console.log('╚══════════════════════════════════════════════════════════╝\n');
|
|
25
|
+
|
|
26
|
+
// 1. Initialize SDK
|
|
27
|
+
console.log('▸ 1. Initialization and Runtime Verification');
|
|
28
|
+
const sdk = new ResonanceSDK({ D: 4096 });
|
|
29
|
+
await sdk.init();
|
|
30
|
+
assert('SDK initialized successfully', sdk._initialized);
|
|
31
|
+
assert('WASM instance is active', sdk.wasmInstance !== null);
|
|
32
|
+
assert('WASM memory is active', sdk.wasmMemory !== null);
|
|
33
|
+
|
|
34
|
+
// 2. Zero-Copy Interface Checks
|
|
35
|
+
console.log('\n▸ 2. Zero-Copy Memory Assertions');
|
|
36
|
+
// Check pointers are non-zero and allocated within WASM linear memory
|
|
37
|
+
assert('vocabCosPtr is allocated', sdk.vocabCosPtr > 0);
|
|
38
|
+
assert('vocabSinPtr is allocated', sdk.vocabSinPtr > 0);
|
|
39
|
+
assert('scoresPtr is allocated', sdk.scoresPtr > 0);
|
|
40
|
+
assert('candidateIndicesPtr is allocated', sdk.candidateIndicesPtr > 0);
|
|
41
|
+
|
|
42
|
+
// Validate shared memory buffers (float arrays point to the exact same buffer)
|
|
43
|
+
const memBuffer = sdk.wasmMemory.buffer;
|
|
44
|
+
assert('WASM memory is an ArrayBuffer', memBuffer instanceof ArrayBuffer);
|
|
45
|
+
|
|
46
|
+
// Try writing a small test slice to candidates ptr and checking it matches WASM buffer
|
|
47
|
+
const testPool = [1, 5, 10, 42];
|
|
48
|
+
const candView = new Int32Array(memBuffer, sdk.candidateIndicesPtr, testPool.length);
|
|
49
|
+
candView.set(testPool);
|
|
50
|
+
|
|
51
|
+
// Check that writing directly updates memory
|
|
52
|
+
const checkCandView = new Int32Array(memBuffer, sdk.candidateIndicesPtr, testPool.length);
|
|
53
|
+
assert('Zero-copy candidate pointer is writable and readable',
|
|
54
|
+
checkCandView[0] === 1 && checkCandView[3] === 42
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
// 3. Memory Footprint / Limits Check
|
|
58
|
+
console.log('\n▸ 3. Memory Footprint Limits Assertions');
|
|
59
|
+
const heapBytes = sdk.wasmMemory.buffer.byteLength;
|
|
60
|
+
const heapMb = heapBytes / (1024 * 1024);
|
|
61
|
+
console.log(` → WASM Linear Memory Allocated: ${heapMb.toFixed(2)} MB`);
|
|
62
|
+
// Assert memory stays well below commercial target limit for large vocabulary (e.g., 1500 MB)
|
|
63
|
+
assert('WASM memory usage is within commercial limits (< 1500 MB)', heapMb < 1500);
|
|
64
|
+
|
|
65
|
+
// 4. OOV Correctness Checks
|
|
66
|
+
console.log('\n▸ 4. Out-of-Vocabulary (OOV) Safety Assertions');
|
|
67
|
+
// Verify <unk> exists in vocab
|
|
68
|
+
assert('<unk> token is at index 0', sdk.vocab[0] === '<unk>');
|
|
69
|
+
assert('<unk> index lookup works', sdk.vocabMap.get('<unk>') === 0);
|
|
70
|
+
|
|
71
|
+
// Run generation with completely unknown words (OOV)
|
|
72
|
+
const oovPrompt = "xyzabc123 qwerty999";
|
|
73
|
+
const result = sdk.generate(oovPrompt, { maxLength: 3 });
|
|
74
|
+
assert('OOV prompt generation completed without crashing', result !== null);
|
|
75
|
+
assert('OOV prompt generated valid output words', result.newTokens.length > 0);
|
|
76
|
+
console.log(` → OOV Prompt: "${oovPrompt}"`);
|
|
77
|
+
console.log(` → Assistant Output: "${result.generatedText}"`);
|
|
78
|
+
|
|
79
|
+
// 5. Morphological Expansion Verification
|
|
80
|
+
console.log('\n▸ 5. Turkish Morphological Expansion Verification');
|
|
81
|
+
const testWord = "kitaplarımızdan";
|
|
82
|
+
const analysis = sdk.analyze(testWord);
|
|
83
|
+
assert('Morphology analysis returns valid object', typeof analysis === 'object');
|
|
84
|
+
assert('Correct root detected', analysis.root === 'kitap');
|
|
85
|
+
assert('Suffixes array populated', analysis.suffixes.includes('lar') && analysis.suffixes.includes('dan'));
|
|
86
|
+
|
|
87
|
+
// ── SUMMARY ───────────────────────────────────────────
|
|
88
|
+
console.log('\n╔══════════════════════════════════════════════════════════╗');
|
|
89
|
+
console.log(`║ RESULTS: ${passed}/${total} PASSED ${failed > 0 ? `(${failed} FAILED)` : '✨ ALL CLEAR'} ║`);
|
|
90
|
+
console.log('╚══════════════════════════════════════════════════════════╝\n');
|
|
91
|
+
|
|
92
|
+
process.exit(failed > 0 ? 1 : 0);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
runTests().catch(e => {
|
|
96
|
+
console.error('Test runner failure:', e);
|
|
97
|
+
process.exit(1);
|
|
98
|
+
});
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Automated Test Suite for @resonance/core Commercial SDK
|
|
3
|
+
* Run with: node sdk/tests/test_commercial_sdk.js
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import assert from 'assert';
|
|
7
|
+
import fs from 'fs';
|
|
8
|
+
import {
|
|
9
|
+
ResonanceEngine,
|
|
10
|
+
LicenseManager,
|
|
11
|
+
LICENSE_TIERS,
|
|
12
|
+
MemoryStorageAdapter,
|
|
13
|
+
FileStorageAdapter
|
|
14
|
+
} from '../index.js';
|
|
15
|
+
|
|
16
|
+
async function runTests() {
|
|
17
|
+
console.log('🧪 Starting Commercial B2B SDK Automated Verification...\n');
|
|
18
|
+
|
|
19
|
+
// ── 1. Cryptographic Offline Licensing Tests ─────────────────
|
|
20
|
+
console.log('Test 1: Cryptographic Offline Licensing...');
|
|
21
|
+
const secret = 'TEST_VENDOR_SECRET_KEY_12345';
|
|
22
|
+
const validKey = LicenseManager.generateLicenseKey({
|
|
23
|
+
tier: 'BUSINESS',
|
|
24
|
+
expiresAt: Date.now() + 100000,
|
|
25
|
+
clientId: 'test-bank'
|
|
26
|
+
}, secret);
|
|
27
|
+
|
|
28
|
+
const licMgr = new LicenseManager(secret);
|
|
29
|
+
const verifyRes = licMgr.verifyLicense(validKey);
|
|
30
|
+
assert.strictEqual(verifyRes.valid, true, 'License should be cryptographically valid');
|
|
31
|
+
assert.strictEqual(verifyRes.tier.name, 'Business', 'Tier should be Business');
|
|
32
|
+
assert.strictEqual(verifyRes.maxNodes, 50000, 'Max nodes should be 50,000');
|
|
33
|
+
|
|
34
|
+
// Test Tampered License
|
|
35
|
+
const tamperedKey = validKey.slice(0, -4) + 'ffff';
|
|
36
|
+
const tamperedRes = licMgr.verifyLicense(tamperedKey);
|
|
37
|
+
assert.strictEqual(tamperedRes.valid, false, 'Tampered license signature must fail');
|
|
38
|
+
|
|
39
|
+
// Test Expired License
|
|
40
|
+
const expiredKey = LicenseManager.generateLicenseKey({
|
|
41
|
+
tier: 'STARTER',
|
|
42
|
+
expiresAt: Date.now() - 1000,
|
|
43
|
+
clientId: 'test-expired'
|
|
44
|
+
}, secret);
|
|
45
|
+
const expiredRes = licMgr.verifyLicense(expiredKey);
|
|
46
|
+
assert.strictEqual(expiredRes.valid, false, 'Expired license must fail');
|
|
47
|
+
console.log('✅ License verification and tamper resistance passed.');
|
|
48
|
+
|
|
49
|
+
// ── 2. Storage Adapter Persistence Tests ─────────────────────
|
|
50
|
+
console.log('\nTest 2: Storage Adapters (Memory & File)...');
|
|
51
|
+
const tempPath = './scratch/test_memory_storage.json';
|
|
52
|
+
const fileStorage = new FileStorageAdapter(tempPath);
|
|
53
|
+
await fileStorage.init();
|
|
54
|
+
await fileStorage.save([{ id: 1, content: 'Test Memory' }]);
|
|
55
|
+
const loaded = await fileStorage.load();
|
|
56
|
+
assert.strictEqual(loaded.length, 1, 'File storage should persist and reload records');
|
|
57
|
+
assert.strictEqual(loaded[0].content, 'Test Memory');
|
|
58
|
+
await fileStorage.clear();
|
|
59
|
+
assert.strictEqual((await fileStorage.load()).length, 0, 'Clear should empty file storage');
|
|
60
|
+
if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath);
|
|
61
|
+
console.log('✅ Storage adapters passed.');
|
|
62
|
+
|
|
63
|
+
// ── 3. Engine Initialization & Ingestion Tests ───────────────
|
|
64
|
+
console.log('\nTest 3: Engine Ingestion (Text & CSV)...');
|
|
65
|
+
const engine = new ResonanceEngine({
|
|
66
|
+
licenseKey: validKey,
|
|
67
|
+
vendorSecret: secret,
|
|
68
|
+
storage: new MemoryStorageAdapter()
|
|
69
|
+
});
|
|
70
|
+
await engine.init();
|
|
71
|
+
|
|
72
|
+
// Ingest Text
|
|
73
|
+
const textIngest = await engine.ingest({
|
|
74
|
+
type: 'text',
|
|
75
|
+
title: 'Ticaret Kanunu',
|
|
76
|
+
data: `
|
|
77
|
+
Madde 1: Türk Ticaret Kanunu, 6102 sayılı kanundur.
|
|
78
|
+
Madde 2: Tacir, bir ticari işletmeyi kısmen de olsa kendi adına işleten kişidir.
|
|
79
|
+
Madde 3: Ticaret şirketleri; kollektif, komandit, anonim, limited ve kooperatif şirketlerden ibarettir.
|
|
80
|
+
`
|
|
81
|
+
});
|
|
82
|
+
assert.strictEqual(textIngest.success, true);
|
|
83
|
+
assert.strictEqual(textIngest.recordsAdded, 3);
|
|
84
|
+
|
|
85
|
+
// Ingest CSV
|
|
86
|
+
const csvIngest = await engine.ingest({
|
|
87
|
+
type: 'csv',
|
|
88
|
+
title: 'Şirket Verileri',
|
|
89
|
+
data: `
|
|
90
|
+
Proje,Açıklama,Durum
|
|
91
|
+
Resonance AI,Yerel Türkçe Bilişsel Çekirdek,Aktif
|
|
92
|
+
Opacus,Otonom Ajan Güvenlik Katmanı,Aktif
|
|
93
|
+
`
|
|
94
|
+
});
|
|
95
|
+
assert.strictEqual(csvIngest.success, true);
|
|
96
|
+
assert.strictEqual(csvIngest.recordsAdded, 2);
|
|
97
|
+
console.log('✅ Document and tabular ingestion passed.');
|
|
98
|
+
|
|
99
|
+
// ── 4. Precision Q&A and Routing Tests ───────────────────────
|
|
100
|
+
console.log('\nTest 4: Precision Q&A Dispatcher...');
|
|
101
|
+
|
|
102
|
+
// Direct fact question
|
|
103
|
+
const q1 = await engine.ask('Tacir kimdir?');
|
|
104
|
+
console.log('Q1 Answer:', q1.answer);
|
|
105
|
+
assert.strictEqual(q1.route, 'memory_qa_detail');
|
|
106
|
+
assert.ok(q1.answer.includes('kendi adına işleten'), 'Should extract definition of tacir');
|
|
107
|
+
assert.ok(q1.latencyMs < 50, 'Latency must be sub-50ms in testing');
|
|
108
|
+
|
|
109
|
+
// Math Gate
|
|
110
|
+
const q2 = await engine.ask('150 * 3 + 50');
|
|
111
|
+
console.log('Q2 Math:', q2.answer);
|
|
112
|
+
assert.strictEqual(q2.route, 'math');
|
|
113
|
+
assert.strictEqual(q2.answer, '500');
|
|
114
|
+
|
|
115
|
+
// Morphology Gate
|
|
116
|
+
const q3 = await engine.ask('bilgisayarlarımızdan');
|
|
117
|
+
console.log('Q3 Morphology:', q3.answer);
|
|
118
|
+
assert.strictEqual(q3.route, 'morphology');
|
|
119
|
+
assert.ok(q3.answer.includes('bilgisayar'));
|
|
120
|
+
|
|
121
|
+
// ── 5. Telemetry & Quota Enforcement ─────────────────────────
|
|
122
|
+
console.log('\nTest 5: Telemetry and Quota...');
|
|
123
|
+
const telemetry = engine.getTelemetry();
|
|
124
|
+
console.log('Telemetry Output:', telemetry);
|
|
125
|
+
assert.strictEqual(telemetry.tier, 'Business');
|
|
126
|
+
assert.strictEqual(telemetry.licenseValid, true);
|
|
127
|
+
assert.ok(telemetry.totalQueries >= 3);
|
|
128
|
+
assert.strictEqual(telemetry.activeNodes, 5);
|
|
129
|
+
|
|
130
|
+
console.log('\n🎉 ALL COMMERCIAL SDK TESTS PASSED SUCCESSFULLY!');
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
runTests().catch(err => {
|
|
134
|
+
console.error('\n❌ TEST FAILED:', err);
|
|
135
|
+
process.exit(1);
|
|
136
|
+
});
|
package/sdk/types.d.ts
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TypeScript Definitions for @resonance/core (Commercial B2B SDK)
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
export interface LicenseTier {
|
|
6
|
+
name: 'Starter' | 'Business' | 'Sovereign';
|
|
7
|
+
maxNodes: number;
|
|
8
|
+
allowedRuntimes: string[];
|
|
9
|
+
features: string[];
|
|
10
|
+
wasmRequired: boolean;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface LicenseVerificationResult {
|
|
14
|
+
valid: boolean;
|
|
15
|
+
tier: LicenseTier;
|
|
16
|
+
expiresAt: Date | null;
|
|
17
|
+
maxNodes: number;
|
|
18
|
+
clientId?: string;
|
|
19
|
+
reason?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface IngestInput {
|
|
23
|
+
data: string | Buffer | ArrayBuffer;
|
|
24
|
+
type?: 'text' | 'pdf' | 'csv' | 'tsv' | 'url';
|
|
25
|
+
title?: string;
|
|
26
|
+
metadata?: Record<string, any>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface IngestRecord {
|
|
30
|
+
query: string;
|
|
31
|
+
content: string;
|
|
32
|
+
confidence: number;
|
|
33
|
+
metadata?: Record<string, any>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface IngestResult {
|
|
37
|
+
success: boolean;
|
|
38
|
+
recordsAdded: number;
|
|
39
|
+
totalMemoryNodes?: number;
|
|
40
|
+
stats?: Record<string, any>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface AskResult {
|
|
44
|
+
answer: string;
|
|
45
|
+
route: string;
|
|
46
|
+
confidence: number;
|
|
47
|
+
latencyMs: number;
|
|
48
|
+
llmBypassed: boolean;
|
|
49
|
+
tier: string;
|
|
50
|
+
metadata?: Record<string, any>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface SummarizeOptions {
|
|
54
|
+
page?: number;
|
|
55
|
+
document?: string;
|
|
56
|
+
mode?: 'concise' | 'single' | 'full';
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface SearchResult {
|
|
60
|
+
content: string;
|
|
61
|
+
score: number;
|
|
62
|
+
metadata?: Record<string, any>;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface TelemetryMetrics {
|
|
66
|
+
activeNodes: number;
|
|
67
|
+
maxNodesQuota: number;
|
|
68
|
+
tier: string;
|
|
69
|
+
licenseValid: boolean;
|
|
70
|
+
totalQueries: number;
|
|
71
|
+
avgLatencyMs: number;
|
|
72
|
+
bypassedLlmCount: number;
|
|
73
|
+
storageType: string;
|
|
74
|
+
uptimeSeconds: number;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface ResonanceConfig {
|
|
78
|
+
licenseKey?: string;
|
|
79
|
+
D?: number;
|
|
80
|
+
storage?: BaseStorageAdapter;
|
|
81
|
+
vendorSecret?: string;
|
|
82
|
+
ingestion?: {
|
|
83
|
+
maxChunkSize?: number;
|
|
84
|
+
overlap?: number;
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export declare class BaseStorageAdapter {
|
|
89
|
+
name: string;
|
|
90
|
+
init(): Promise<void>;
|
|
91
|
+
load(): Promise<any[]>;
|
|
92
|
+
save(records: any[]): Promise<boolean>;
|
|
93
|
+
clear(): Promise<boolean>;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export declare class MemoryStorageAdapter extends BaseStorageAdapter {}
|
|
97
|
+
export declare class FileStorageAdapter extends BaseStorageAdapter {
|
|
98
|
+
constructor(filePath?: string);
|
|
99
|
+
}
|
|
100
|
+
export declare class IndexedDBStorageAdapter extends BaseStorageAdapter {
|
|
101
|
+
constructor(dbName?: string, storeName?: string);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export declare class LicenseManager {
|
|
105
|
+
constructor(vendorSecret?: string);
|
|
106
|
+
static generateLicenseKey(opts: {
|
|
107
|
+
tier: 'STARTER' | 'BUSINESS' | 'SOVEREIGN';
|
|
108
|
+
expiresAt: number | Date;
|
|
109
|
+
maxNodes?: number;
|
|
110
|
+
clientId?: string;
|
|
111
|
+
}, secret?: string): string;
|
|
112
|
+
verifyLicense(key: string): LicenseVerificationResult;
|
|
113
|
+
canUseFeature(featureName: string): boolean;
|
|
114
|
+
checkNodeQuota(currentTotal: number, addingCount?: number): boolean;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export declare class IngestionEngine {
|
|
118
|
+
constructor(options?: { maxChunkSize?: number; overlap?: number });
|
|
119
|
+
ingest(input: IngestInput): Promise<{
|
|
120
|
+
success: boolean;
|
|
121
|
+
records: IngestRecord[];
|
|
122
|
+
stats: Record<string, any>;
|
|
123
|
+
}>;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export declare class GHRLatticeMemory {
|
|
127
|
+
D: number;
|
|
128
|
+
cellSize: number;
|
|
129
|
+
sigma: number;
|
|
130
|
+
cells: any[];
|
|
131
|
+
constructor(config?: { D?: number; cellSize?: number; sigma?: number; seed?: number; numTables?: number; numProjections?: number });
|
|
132
|
+
encodePacket(phases: Float64Array, channelIndex: number): { real: Float64Array; imag: Float64Array; channel: number };
|
|
133
|
+
insert(factVector: { id: string; phases: Float64Array }, metadata?: Record<string, any>): any;
|
|
134
|
+
query(queryVector: { id?: string; phases: Float64Array }, topK?: number): Array<{ item: any; score: number; rank: number; latencyMs: number }>;
|
|
135
|
+
calculateSIR(queryVector: { id?: string; phases: Float64Array }, targetId: string): number;
|
|
136
|
+
readonly stats: { D: number; totalCells: number; totalItems: number; cellSizeLimit: number; sigma: number };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export declare class ResonanceEngine {
|
|
140
|
+
constructor(config?: ResonanceConfig);
|
|
141
|
+
init(): Promise<this>;
|
|
142
|
+
ask(prompt: string, options?: Record<string, any>): Promise<AskResult>;
|
|
143
|
+
ingest(input: IngestInput): Promise<IngestResult>;
|
|
144
|
+
summarize(opts?: SummarizeOptions): string;
|
|
145
|
+
search(query: string, limit?: number): SearchResult[];
|
|
146
|
+
clearMemory(): Promise<boolean>;
|
|
147
|
+
onConflict(handler: (existing: any, incoming: any) => void): void;
|
|
148
|
+
getTelemetry(): TelemetryMetrics;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export { ResonanceEngine as ResonanceSDK };
|
|
152
|
+
export default ResonanceEngine;
|