@memoryintelligence/sdk 2.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,691 @@
1
+ ## Memory Intelligence JavaScript / TypeScript SDK
2
+
3
+ Official JS/TS SDK for building web apps, browser extensions, integrations, and Node.js services powered by Memory Intelligence.
4
+
5
+ The JavaScript / TypeScript SDK enables developers to interact with the Memory Intelligence Operating System from:
6
+ • Web applications
7
+ • Browser extensions
8
+ • Node.js servers
9
+ • Edge runtimes (Cloudflare Workers, Vercel, Bun, Deno)
10
+ • React/Next.js frontends
11
+ • Electron/desktop applications
12
+
13
+ It provides a fully typed, modern, secure client for working with UMOs, semantic search, hybrid retrieval, timeline APIs, agents, collections, and the meaning graph.
14
+
15
+
16
+
17
+ ## ⚠️ SECURITY WARNING
18
+
19
+ **🔐 Backend/Server-Side Use Only**
20
+
21
+ This SDK is designed for **backend and server-side use only**.
22
+
23
+ **❌ DO NOT use this SDK in client-side browser code** - your API key will be exposed to anyone who opens the developer console or inspects network requests.
24
+
25
+ **✅ Correct Usage:**
26
+ - Next.js API routes
27
+ - Node.js servers
28
+ - Express/Fastify backends
29
+ - Serverless functions (Vercel, Netlify, AWS Lambda)
30
+ - Cloudflare Workers (with secret environment variables)
31
+
32
+ **❌ Incorrect Usage:**
33
+ - React components running in the browser
34
+ - Vue/Svelte client-side code
35
+ - Static HTML pages
36
+ - Browser extensions (content scripts)
37
+
38
+ 📖 **Read the security guide:** [docs/SECURITY.md](./docs/SECURITY.md)
39
+
40
+
41
+
42
+ 1. Features
43
+
44
+ TypeScript-First Architecture
45
+ • Full type safety
46
+ • Autocompletion for all API models
47
+ • Tightly aligned with MemoryOS schema
48
+ • SDK-generated types remain stable across versions
49
+
50
+ Browser + Node Support
51
+ • Works in React, Next.js, Vue, Svelte
52
+ • Works in Cloudflare Workers, Node, Bun, Deno
53
+ • Zero heavy dependencies
54
+ • ES modules + CommonJS builds
55
+
56
+ Performance & Reliability
57
+ • Built-in request caching
58
+ • Automatic retries
59
+ • Adaptive backoff
60
+ • AbortController support
61
+ • Connection reuse for Node environments
62
+
63
+ Meaning & Privacy Enforcement
64
+ • UMO validation helpers
65
+ • governance-aware field masking
66
+ • ULID identity enforcement
67
+ • provenance hashing utilities
68
+ • strict prevention of raw external ID leakage
69
+
70
+ Developer Ergonomics
71
+ • Async/await everywhere
72
+ • Tree-shakeable modules
73
+ • Optional React hooks package
74
+ **Step 1: Environment Variables**
75
+
76
+ Create a `.env` file (never commit this!):
77
+
78
+ ```bash
79
+ MI_API_KEY=mi_sk_test_your_secret_key_here
80
+ ```
81
+
82
+ Add `.env` to your `.gitignore`:
83
+
84
+ ```bash
85
+ # .gitignore
86
+ .env
87
+ .env.local
88
+ .env.*.local
89
+ ```
90
+
91
+ **Step 2: Initialize Client (Server-Side Only)**
92
+
93
+ ```typescript
94
+ // ✅ CORRECT: Next.js API Route (server-side)
95
+ // app/api/process/route.ts
96
+ import { MemoryClient } from '@memoryintelligence/sdk';
97
+
98
+ const client = new MemoryClient({
99
+ apiKey: process.env.MI_API_KEY! // ✅ Safe - runs on server
100
+ });
101
+
102
+ export async function POST(request: Request) {
103
+ const { content } = await request.json();
104
+ const umo = await client.umo.process(content);
105
+ return Response.json({ umo });
106
+ }
107
+ ```
108
+
109
+ ```typescript
110
+ // ❌ WRONG: React Component (client-side)
111
+ // components/MyComponent.tsx
112
+ import { MemoryClient } from '@memoryintelligence/sdk';
113
+
114
+ function MyComponent() {
115
+ const client = new MemoryClient({
116
+ apiKey: 'mi_sk_xxx' // ❌ EXPOSED! Never do this!
117
+ });
118
+ // ...
119
+ }
120
+ ```
121
+
122
+ **See `.env.example` for all configuration options.**
123
+ npm install @memoryintelligence/sdk
124
+
125
+ Yarn
126
+
127
+ yarn add @memoryintelligence/sdk
128
+
129
+ PNPM
130
+
131
+ pnpm add @memoryintelligence/sdk
132
+
133
+
134
+
135
+
136
+ 3. Setup
137
+
138
+ import { MemoryClient } from "@memory-intelligence/sdk";
139
+
140
+ const client = new MemoryClient({
141
+ apiKey: process.env.MI_API_KEY,
142
+ apiUrl: "https://api.memory-intelligence.com"
143
+ });
144
+
145
+ You may also use MI_API_KEY and MI_API_URL environment variables globally.
146
+
147
+
148
+
149
+ 4. Creating Memories
150
+
151
+ Simple Text Memory
152
+
153
+ const umo = await client.memories.create({
154
+ content: "Design meeting notes about Q2 strategy."
155
+ });
156
+
157
+ With Tags + Context
158
+
159
+ const umo = await client.memories.create({
160
+ content: "Interview with prospective client.",
161
+ tags: ["interview", "client"],
162
+ context: { department: "sales" }
163
+ });
164
+
165
+ With Provenance Hash
166
+
167
+ import { computeHash } from "@memory-intelligence/sdk";
168
+
169
+ const umo = await client.memories.create({
170
+ content: "Draft press release.",
171
+ provenanceHash: computeHash("Draft press release.")
172
+ });
173
+
174
+
175
+
176
+
177
+ 5. Searching Memories
178
+
179
+ Semantic Search
180
+
181
+ const results = await client.search.semantic("project planning");
182
+
183
+ Hybrid Search
184
+
185
+ const results = await client.search.hybrid({
186
+ query: "customer onboarding",
187
+ limit: 20
188
+ });
189
+
190
+ Entity-Based Search
191
+
192
+ const results = await client.search.byEntity({
193
+ entity: "OpenAI",
194
+ limit: 10
195
+ });
196
+
197
+ Graph Neighborhood
198
+
199
+ const neighbors = await client.graph.neighbors({
200
+ umoId: "01HK..."
201
+ });
202
+
203
+
204
+
205
+
206
+ 6. Timeline Queries
207
+
208
+ Time Window Retrieval
209
+
210
+ const window = await client.timeline.range({
211
+ start: "2025-01-01",
212
+ end: "2025-02-02"
213
+ });
214
+
215
+ Significance-Based Resurfacing
216
+
217
+ const resurfaced = await client.timeline.resurface({ limit: 12 });
218
+
219
+
220
+
221
+
222
+ 7. Agents API
223
+
224
+ Summarize a Memory
225
+
226
+ const summary = await client.agents.summarize({ umoId: "01HK..." });
227
+
228
+ Generate Insights
229
+
230
+ const insights = await client.agents.insights({
231
+ collectionId: "col_001"
232
+ });
233
+
234
+ Narrative Generation
235
+
236
+ const narrative = await client.agents.narrative({
237
+ umoIds: ["01A..", "01B.."]
238
+ });
239
+
240
+
241
+
242
+
243
+ 8. Collections
244
+
245
+ const col = await client.collections.create({
246
+ name: "Research Articles"
247
+ });
248
+
249
+ await client.collections.add({
250
+ collectionId: col.id,
251
+ umoId: "01HG..."
252
+ });
253
+
254
+ Retrieve:
255
+
256
+ const items = await client.collections.get({ collectionId: col.id });
257
+
258
+
259
+
260
+
261
+ 9. Response Types & Safety
262
+
263
+ All responses are strongly typed:
264
+
265
+ type UMO = Awaited<ReturnType<typeof client.memories.get>>;
266
+
267
+ SDK includes types for:
268
+ • UMO
269
+ • SearchResult
270
+ • TimelineWindow
271
+ • GraphNode
272
+ • ClusterSummary
273
+ • AgentSummary
274
+ • GovernanceError
275
+ • ProvenanceRecord
276
+
277
+
278
+
279
+ 10. Error Handling
280
+
281
+ import {
282
+ AuthenticationError,
283
+ ValidationError,
284
+ GovernanceError,
285
+ RateLimitError,
286
+ ServerError
287
+ } from "@memory-intelligence/sdk";
288
+
289
+ try {
290
+ await client.memories.create({ content: null });
291
+ } catch (err) {
292
+ if (err instanceof ValidationError) {
293
+ console.error("Invalid input:", err.message);
294
+ }
295
+ }
296
+
297
+
298
+
299
+
300
+ 11. Request Caching
301
+
302
+ Automatic caching for safe GET operations:
303
+
304
+ const results = await client.search.semantic("meaning", { cache: true });
305
+
306
+ Custom caches may be injected:
307
+
308
+ const client = new MemoryClient({
309
+ apiKey: "...",
310
+ cacheProvider: customCache
311
+ });
312
+
313
+
314
+
315
+
316
+ 12. Abort Controllers
317
+
318
+ const controller = new AbortController();
319
+
320
+ const promise = client.search.semantic("long query", {
321
+ signal: controller.signal
322
+ });
323
+
324
+ // cancel
325
+ controller.abort();
326
+
327
+
328
+
329
+
330
+ 13. Browser Compatibility
331
+
332
+ CDN Build
333
+
334
+ <script src="https://cdn.memory-intelligence.com/sdk.js"></script>
335
+ <script>
336
+ const client = new MemoryIntelligence.MemoryClient({
337
+ apiKey: "YOUR_KEY"
338
+ });
339
+
340
+ client.search.semantic("example").then(console.log);
341
+ </script>
342
+
343
+ Supports:
344
+ • Chrome
345
+ • Firefox
346
+ • Safari
347
+ • Edge
348
+ • WebExtensions (browser extensions)
349
+
350
+
351
+
352
+ 14. React Hooks (Optional Package)
353
+
354
+ Separate package: @memoryintelligence/react
355
+
356
+ npm install @memoryintelligence/react
357
+
358
+ **Provider Setup:**
359
+
360
+ ```typescript
361
+ import { MemoryClientProvider } from '@memoryintelligence/react';
362
+ import { MemoryClient } from '@memoryintelligence/sdk';
363
+
364
+ const client = new MemoryClient({ apiKey: 'your-key' });
365
+
366
+ function App() {
367
+ return (
368
+ <MemoryClientProvider client={client}>
369
+ <YourApp />
370
+ </MemoryClientProvider>
371
+ );
372
+ }
373
+ ```
374
+
375
+ **Available Hooks:**
376
+
377
+ ```typescript
378
+ import {
379
+ useMemoryClient,
380
+ useDriftSubscription,
381
+ useComputeProgress,
382
+ useMemorySearch,
383
+ useMemoryProcess,
384
+ } from '@memoryintelligence/react';
385
+
386
+ // Search memories
387
+ function SearchBox() {
388
+ const { search, data, loading, error } = useMemorySearch();
389
+
390
+ return (
391
+ <input onChange={e => search(e.target.value)} />
392
+ );
393
+ }
394
+
395
+ // Process content
396
+ function CaptureForm() {
397
+ const { process, data, loading } = useMemoryProcess();
398
+
399
+ const handleSubmit = async (content: string) => {
400
+ await process({ content, type: 'text/plain' });
401
+ };
402
+ }
403
+
404
+ // Monitor drift updates
405
+ function DriftMonitor() {
406
+ const { updates, connected } = useDriftSubscription({
407
+ entityUlids: ['01ARZ3ND...']
408
+ });
409
+
410
+ return <div>{updates.length} drift updates</div>;
411
+ }
412
+
413
+ // Track compute progress
414
+ function ProgressTracker({ operationId }: { operationId: string }) {
415
+ const { progress, result, isComplete } = useComputeProgress(operationId);
416
+
417
+ return <div>{progress?.percentage}% complete</div>;
418
+ }
419
+ ```
420
+
421
+
422
+
423
+ 15. Streaming Utilities (Phase 4)
424
+
425
+ For processing large datasets efficiently:
426
+
427
+ **Batch Processing:**
428
+
429
+ ```typescript
430
+ import { MemoryClient, UMOStreamProcessor } from '@memoryintelligence/sdk';
431
+
432
+ const client = new MemoryClient({ apiKey: 'your-key' });
433
+ const processor = new UMOStreamProcessor(client);
434
+
435
+ // Process 1000 items in batches
436
+ const items = Array.from({ length: 1000 }, (_, i) => ({
437
+ content: `Memory ${i}`,
438
+ type: 'text/plain' as const,
439
+ }));
440
+
441
+ for await (const umo of processor.processBatch({
442
+ items,
443
+ config: {
444
+ chunkSize: 10, // Process 10 at a time
445
+ concurrency: 3, // Max 3 concurrent requests
446
+ onProgress: (done, total) => {
447
+ console.log(`${done}/${total} processed`);
448
+ },
449
+ },
450
+ })) {
451
+ // Each UMO is available as it's processed
452
+ console.log('Processed:', umo.umo_id);
453
+ }
454
+ ```
455
+
456
+ **Batch Search:**
457
+
458
+ ```typescript
459
+ // Execute multiple searches
460
+ for await (const result of processor.searchBatch({
461
+ queries: ['AI', 'machine learning', 'neural networks'],
462
+ searchOptions: { limit: 5 },
463
+ })) {
464
+ console.log(`${result.query}: ${result.results.length} results`);
465
+ }
466
+ ```
467
+
468
+ **Paginated Search:**
469
+
470
+ ```typescript
471
+ import { SearchResultStream } from '@memoryintelligence/sdk';
472
+
473
+ const stream = new SearchResultStream(client);
474
+
475
+ for await (const page of stream.paginate('artificial intelligence', {
476
+ pageSize: 20,
477
+ maxResults: 100,
478
+ })) {
479
+ console.log(`Page: ${page.length} results`);
480
+ }
481
+ ```
482
+
483
+ **Progress Tracking:**
484
+
485
+ ```typescript
486
+ import { ProgressTracker } from '@memoryintelligence/sdk';
487
+
488
+ const tracker = new ProgressTracker(1000, (progress) => {
489
+ console.log(`${progress.percentage.toFixed(1)}% - ETA: ${progress.eta}s`);
490
+ });
491
+
492
+ // Update as you process
493
+ tracker.update(10); // Processed 10 more items
494
+ ```
495
+
496
+ See `examples/streaming.ts` for more patterns.
497
+
498
+
499
+
500
+ 16. React Native Support (Phase 4)
501
+
502
+ The SDK works in React Native with proper polyfills.
503
+
504
+ **Installation:**
505
+
506
+ ```bash
507
+ npm install @memoryintelligence/sdk
508
+ npm install react-native-get-random-values whatwg-fetch abortcontroller-polyfill text-encoding
509
+ ```
510
+
511
+ **Setup (App.tsx):**
512
+
513
+ ```typescript
514
+ // Import polyfills FIRST!
515
+ import 'react-native-get-random-values';
516
+ import 'whatwg-fetch';
517
+ import 'abortcontroller-polyfill/dist/polyfill-patch-fetch';
518
+ import 'text-encoding';
519
+
520
+ import {
521
+ checkReactNativeCompatibility,
522
+ createReactNativeClient,
523
+ } from '@memoryintelligence/sdk';
524
+
525
+ // Check compatibility
526
+ const compat = checkReactNativeCompatibility();
527
+ if (!compat.compatible) {
528
+ console.warn('Missing:', compat.missing);
529
+ console.warn('Install:', compat.polyfillsAvailable);
530
+ }
531
+
532
+ // Create client
533
+ const client = createReactNativeClient('your-api-key');
534
+
535
+ // Use normally
536
+ const result = await client.umo.process({
537
+ content: 'React Native memory',
538
+ type: 'text/plain',
539
+ });
540
+ ```
541
+
542
+ **Compatibility Utilities:**
543
+
544
+ ```typescript
545
+ import { ReactNativeUtils } from '@memoryintelligence/sdk';
546
+
547
+ // Check if running in RN
548
+ if (ReactNativeUtils.isReactNative()) {
549
+ console.log('Running in React Native');
550
+ }
551
+
552
+ // Get required polyfills
553
+ const polyfills = ReactNativeUtils.getRecommendedPolyfills();
554
+ console.log('Install:', polyfills);
555
+
556
+ // Get install command
557
+ const cmd = ReactNativeUtils.getInstallCommand();
558
+ // => "npm install react-native-get-random-values whatwg-fetch ..."
559
+ ```
560
+
561
+ See `examples/react-native.tsx` for a complete app example.
562
+
563
+
564
+
565
+ 17. Governance & Identity Protections
566
+
567
+ Automatically enforced:
568
+ • external IDs → ULIDs
569
+ • forbidden fields stripped before request
570
+ • provenance hashing
571
+ • p50/p95 audit logging hooks
572
+ • masking of governed content
573
+
574
+ JS SDK ensures meaning-safe ingestion & retrieval.
575
+
576
+
577
+
578
+ 16. Node.js Service Examples
579
+
580
+ Batch Ingestion
581
+
582
+ await client.bulk.ingest([
583
+ { content: "Note 1" },
584
+ { content: "Note 2" }
585
+ ]);
586
+
587
+ ETL + Export
588
+
589
+ const dump = await client.bulk.export({
590
+ since: "2025-01-01",
591
+ includeProvenance: true
592
+ });
593
+
594
+
595
+
596
+
597
+ 17. E2E Testing (Phase 4)
598
+
599
+ Run tests against the live API to verify end-to-end functionality.
600
+
601
+ **Setup:**
602
+
603
+ ```bash
604
+ # Set your test API key
605
+ export MI_TEST_API_KEY=mi_sk_test_xxx
606
+
607
+ # Run E2E tests
608
+ npm run test:e2e
609
+ ```
610
+
611
+ **Testing Features:**
612
+ - ✅ UMO processing and retrieval
613
+ - ✅ Semantic search
614
+ - ✅ UMO matching and similarity
615
+ - ✅ Explainability
616
+ - ✅ Provenance verification
617
+ - ✅ WebSocket subscriptions (drift, compute)
618
+ - ✅ Rate limiting
619
+ - ✅ Error handling
620
+
621
+ E2E tests automatically clean up created test data!
622
+
623
+ **Skip E2E Tests:**
624
+
625
+ ```bash
626
+ # Run only unit tests (default)
627
+ npm test
628
+
629
+ # Explicitly run unit tests
630
+ npm run test:unit
631
+ ```
632
+
633
+ See `docs/E2E_TESTING.md` for complete guide.
634
+
635
+
636
+
637
+ 18. Edge Runtime Support
638
+
639
+ Compatible with:
640
+ • Cloudflare Workers
641
+ • Vercel Edge Functions
642
+ • Bun
643
+ • Deno
644
+
645
+ export default {
646
+ async fetch(req, env) {
647
+ const client = new MemoryClient({ apiKey: env.KEY });
648
+ return Response.json(await client.search.semantic("edge test"));
649
+ }
650
+ };
651
+
652
+
653
+
654
+
655
+ 19. Roadmap
656
+
657
+ **Completed (Phase 4):**
658
+ • ✅ Streaming search results and batch processing
659
+ • ✅ E2E testing against live API
660
+ • ✅ React Native compatibility layer
661
+ • ✅ WebSocket subscriptions (drift, compute)
662
+ • ✅ React hooks package
663
+
664
+ **Upcoming Enhancements:**
665
+ • WebAssembly-based local summarizer
666
+ • Browser-side meaning compression helpers
667
+ • Built-in provenance visualizer
668
+ • UMO schema validator for frontend forms
669
+ • Offline-first mode with sync
670
+ • GraphQL API support
671
+ • Vue and Svelte framework packages
672
+
673
+
674
+
675
+ 20. Summary
676
+
677
+ The JavaScript/TypeScript SDK is the official, high-performance, meaning-first client for interacting with Memory Intelligence from any JavaScript environment.
678
+
679
+ It provides:
680
+ • typed UMO creation
681
+ • meaning-aware search
682
+ • timeline access
683
+ • graph exploration
684
+ • collections management
685
+ • agent execution
686
+ • governance compliance
687
+ • production-grade reliability
688
+
689
+ It is the foundation for building MemorySpace-like apps, browser extensions, integrations, dashboards, and enterprise systems in the JavaScript ecosystem.
690
+
691
+