nsr-nodejs 0.3.1

Node.js bindings for the NSR (Neuro-Symbolic Recursive) AI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
# @stateset/nsr

Node.js bindings for the NSR (Neuro-Symbolic Recursive) AI framework.

NSR is a state-of-the-art hybrid AI framework that combines neural network pattern recognition with symbolic logical reasoning for robust, explainable AI systems. These native bindings provide high-performance access to the NSR Machine from Node.js and TypeScript applications.

## Installation

```bash
npm install @stateset/nsr
```

## Requirements

- Node.js >= 16
- Supported platforms:
  - macOS (x64, ARM64)
  - Linux (x64, ARM64, glibc and musl)
  - Windows (x64, ARM64)

## Quick Start

```typescript
import { NSRMachine, GroundedInput, SemanticValue, TrainingExample } from '@stateset/nsr';

// Create a machine using the SCAN preset (compositional generalization)
const machine = scanMachine();

// Or create with custom configuration
const customMachine = new NSRMachineBuilder()
  .embeddingDim(64)
  .hiddenSize(128)
  .addSymbol('walk')
  .addSymbol('run')
  .addSymbol('jump')
  .build();

// Create training examples
const examples = [
  TrainingExample.fromText('walk', SemanticValue.actions(['WALK'])),
  TrainingExample.fromText('run', SemanticValue.actions(['RUN'])),
  TrainingExample.fromText('jump', SemanticValue.actions(['JUMP'])),
  TrainingExample.fromText('walk twice', SemanticValue.actions(['WALK', 'WALK'])),
];

// Train the machine
const stats = machine.train(examples);
console.log(`Trained on ${stats.totalExamples} examples in ${stats.trainingTimeMs}ms`);

// Run inference
const result = machine.infer([GroundedInput.text('jump twice')]);
console.log(`Output: ${result.output()}`);
console.log(`Confidence: ${result.confidence()}`);
```

## Features

- **Grounded Symbol System (GSS)**: Unified representation combining perception, syntax, and semantics
- **Neural Perception**: Maps raw inputs (text, numbers, images) to symbol probabilities
- **Program Synthesis**: Learns functional programs for semantic computation
- **Compositional Generalization**: Achieves near-perfect accuracy on SCAN, PCFG, HINT, and COGS benchmarks
- **TypeScript Support**: Full type definitions included

## API Reference

### Input Types

#### `GroundedInput`

Raw input to the NSR system.

```typescript
// Create different input types
const text = GroundedInput.text('hello world');
const num = GroundedInput.number(42.0);
const img = GroundedInput.image(pixelData, width, height, channels);
const emb = GroundedInput.embedding([0.1, 0.2, 0.3, ...]);
const nil = GroundedInput.nil();

// Check input type
text.isText();    // true
text.isNumber();  // false
text.isNil();     // false

// Get value
text.asText();    // 'hello world'
num.asNumber();   // 42.0
```

### Output Types

#### `SemanticValue`

Computed semantic output from NSR inference.

```typescript
// Create different output types
const int = SemanticValue.integer(42);
const float = SemanticValue.float(3.14);
const bool = SemanticValue.boolean(true);
const str = SemanticValue.string('result');
const sym = SemanticValue.symbol('WALK');
const actions = SemanticValue.actions(['WALK', 'TURN_LEFT', 'WALK']);
const list = SemanticValue.list([SemanticValue.integer(1), SemanticValue.integer(2)]);
const nil = SemanticValue.null();

// Get values
int.asInteger();      // 42
float.asFloat();      // 3.14
str.asString();       // 'result'
actions.asActions();  // ['WALK', 'TURN_LEFT', 'WALK']

// Check type
nil.isNull();   // true
nil.isError();  // false
```

### Program Types

#### `Primitive`

Built-in primitive operations for program synthesis.

```typescript
// Arithmetic
Primitive.add();  // Addition
Primitive.sub();  // Subtraction
Primitive.mul();  // Multiplication
Primitive.div();  // Division

// Comparison
Primitive.eq();   // Equality
Primitive.lt();   // Less than
Primitive.gt();   // Greater than

// Logic
Primitive.and();  // Logical AND
Primitive.or();   // Logical OR
Primitive.not();  // Logical NOT

// List operations
Primitive.cons(); // List construction
Primitive.car();  // First element
Primitive.cdr();  // Rest of list

// Utility
Primitive.identity();  // Identity function

// Get info
const add = Primitive.add();
add.arity();  // 2
add.name();   // 'add'
```

#### `Program`

Functional programs for computing semantics.

```typescript
// Constant program
const constProg = Program.constant(SemanticValue.integer(42));

// Variable reference (for lambda bodies)
const varProg = Program.var(0);

// Child reference (access child nodes in GSS)
const childProg = Program.child(0);

// Primitive application
const addProg = Program.primitive(Primitive.add(), [
  Program.child(0),
  Program.child(1)
]);

// Lambda abstraction
const lambdaProg = Program.lambda(2, addProg);

// Function application
const applyProg = Program.apply(lambdaProg, [
  Program.constant(SemanticValue.integer(1)),
  Program.constant(SemanticValue.integer(2))
]);

// Conditional
const condProg = Program.ifThenElse(
  Program.child(0),
  Program.constant(SemanticValue.string('yes')),
  Program.constant(SemanticValue.string('no'))
);

// Program metrics
constProg.depth();       // 1
constProg.size();        // 1
constProg.isConstant();  // true
```

### Training

#### `TrainingExample`

A single training example for the NSR machine.

```typescript
// Create from inputs and output
const example = new TrainingExample(
  [GroundedInput.text('walk'), GroundedInput.text('twice')],
  SemanticValue.actions(['WALK', 'WALK']),
  0.5  // optional difficulty (0.0 - 1.0)
);

// Convenience constructors
const textExample = TrainingExample.fromText('hello', SemanticValue.string('HELLO'));
const tokenExample = TrainingExample.fromTokens(['walk', 'left'], SemanticValue.actions(['TURN_LEFT', 'WALK']));

// Properties
example.difficulty;   // 0.5
example.inputCount;   // 2
```

#### `TrainingStats`

Statistics returned from training.

```typescript
interface TrainingStats {
  totalExamples: number;       // Number of examples trained on
  successfulAbductions: number; // Successful program inductions
  trainingTimeMs: number;       // Training duration in milliseconds
}
```

### Machine Configuration

#### `NSRConfig`

Configuration options for the NSR machine.

```typescript
interface NSRConfig {
  embeddingDim: number;     // Embedding vector dimension (default: 64)
  hiddenSize: number;       // Hidden layer size (default: 128)
  maxSeqLen: number;        // Maximum sequence length (default: 64)
  beamWidth: number;        // Beam search width (default: 5)
  enableSynthesis: boolean; // Enable program synthesis (default: true)
  maxProgramDepth: number;  // Maximum program depth (default: 6)
}
```

### NSRMachine

The main neuro-symbolic reasoning machine.

#### Construction

```typescript
// Default machine
const machine = new NSRMachine();

// With configuration
const configuredMachine = NSRMachine.withConfig({
  embeddingDim: 128,
  hiddenSize: 256,
  maxSeqLen: 128,
  beamWidth: 10,
  enableSynthesis: true,
  maxProgramDepth: 8
});

// Using builder (recommended)
const builtMachine = new NSRMachineBuilder()
  .embeddingDim(64)
  .hiddenSize(128)
  .maxSeqLen(64)
  .beamWidth(5)
  .addSymbol('walk')
  .addSymbol('run')
  .enableSynthesis(true)
  .withExplainability()
  .build();
```

#### Inference

```typescript
const result = machine.infer([GroundedInput.text('walk twice')]);

result.output();         // Output value as string
result.confidence();     // Confidence score (0.0 - 1.0)
result.symbols();        // Predicted symbol sequence
result.nodeCount();      // Number of GSS nodes
result.logProbability(); // Log probability of prediction
```

#### Training

```typescript
const examples = [
  TrainingExample.fromText('a', SemanticValue.integer(1)),
  TrainingExample.fromText('b', SemanticValue.integer(2)),
];

const stats = machine.train(examples);
// stats.totalExamples: 2
// stats.successfulAbductions: 2
// stats.trainingTimeMs: 15
```

#### Evaluation

```typescript
const testExamples = [
  TrainingExample.fromText('a', SemanticValue.integer(1)),
  TrainingExample.fromText('c', SemanticValue.integer(3)),
];

const result = machine.evaluate(testExamples);
// result.accuracy: 0.5
// result.correct: 1
// result.total: 2
```

#### Symbol Management

```typescript
// Add symbols
const walkId = machine.addSymbol('walk');
const ids = machine.addSymbols(['run', 'jump', 'turn']);

// Query symbols
machine.getSymbolName(0);      // 'walk'
machine.getSymbolId('walk');   // 0
machine.getAllSymbols();       // ['walk', 'run', 'jump', 'turn']
machine.vocabularySize;        // 4
```

#### Statistics

```typescript
const stats = machine.statistics;
// stats.trainingExamples: 100
// stats.successfulInferences: 95
// stats.programsLearned: 12
// stats.vocabularySize: 20
```

### Preset Machines

Pre-configured machines for standard benchmarks:

```typescript
import { scanMachine, pcfgMachine, hintMachine, cogsMachine } from '@stateset/nsr';

// SCAN: Compositional command interpretation
// "walk twice" -> ['WALK', 'WALK']
const scan = scanMachine();

// PCFG: Probabilistic context-free grammar tasks
// Character-level sequence transduction
const pcfg = pcfgMachine();

// HINT: Hierarchical arithmetic expressions
// "( 2 + 3 ) * 4" -> 20
const hint = hintMachine();

// COGS: Compositional generalization challenge
// Semantic parsing with systematic generalization
const cogs = cogsMachine();
```

### Utility Functions

```typescript
import { version } from '@stateset/nsr';

// Get library version
console.log(version()); // '0.2.0'
```

## Examples

### SCAN-style Command Learning

```typescript
import { scanMachine, GroundedInput, SemanticValue, TrainingExample } from '@stateset/nsr';

const machine = scanMachine();

// Train on primitive commands
const trainData = [
  TrainingExample.fromText('walk', SemanticValue.actions(['WALK'])),
  TrainingExample.fromText('run', SemanticValue.actions(['RUN'])),
  TrainingExample.fromText('jump', SemanticValue.actions(['JUMP'])),
  TrainingExample.fromText('turn left', SemanticValue.actions(['TURN_LEFT'])),
  TrainingExample.fromText('turn right', SemanticValue.actions(['TURN_RIGHT'])),
  // Compositional examples
  TrainingExample.fromText('walk twice', SemanticValue.actions(['WALK', 'WALK'])),
  TrainingExample.fromText('jump and walk', SemanticValue.actions(['JUMP', 'WALK'])),
];

machine.train(trainData);

// Test compositional generalization
const result = machine.infer([GroundedInput.text('run twice and turn left')]);
console.log(result.output()); // ['RUN', 'RUN', 'TURN_LEFT']
```

### Arithmetic Expression Evaluation

```typescript
import { hintMachine, GroundedInput, SemanticValue, TrainingExample } from '@stateset/nsr';

const machine = hintMachine();

// Train on arithmetic examples
const trainData = [
  TrainingExample.fromText('1 + 2', SemanticValue.integer(3)),
  TrainingExample.fromText('3 * 4', SemanticValue.integer(12)),
  TrainingExample.fromText('( 2 + 3 ) * 2', SemanticValue.integer(10)),
];

machine.train(trainData);

// Evaluate new expressions
const result = machine.infer([GroundedInput.text('( 1 + 2 ) * 3')]);
console.log(result.output()); // 9
```

### Custom Symbol Vocabulary

```typescript
import { NSRMachineBuilder, GroundedInput, SemanticValue, TrainingExample } from '@stateset/nsr';

// Build a machine for sentiment analysis
const machine = new NSRMachineBuilder()
  .embeddingDim(128)
  .hiddenSize(256)
  .addSymbol('positive')
  .addSymbol('negative')
  .addSymbol('neutral')
  .enableSynthesis(false)  // Classification only
  .build();

const trainData = [
  TrainingExample.fromText('great product', SemanticValue.symbol('positive')),
  TrainingExample.fromText('terrible experience', SemanticValue.symbol('negative')),
  TrainingExample.fromText('it was okay', SemanticValue.symbol('neutral')),
];

machine.train(trainData);

const result = machine.infer([GroundedInput.text('amazing quality')]);
console.log(result.output()); // 'positive'
console.log(result.confidence()); // 0.92
```

## Building from Source

### Prerequisites

- Rust 1.75+
- Node.js 16+
- npm or yarn

### Build Steps

```bash
# Clone the repository
git clone https://github.com/stateset/stateset-nsr
cd stateset-nsr/nodejs

# Install dependencies
npm install

# Build native addon (release)
npm run build

# Build native addon (debug)
npm run build:debug

# Run tests
npm test
```

### Cross-compilation

The package uses NAPI-RS for cross-platform native addons. Pre-built binaries are provided for common platforms. To build for other platforms:

```bash
# Build for all platforms
npm run artifacts

# Build universal binary (macOS)
npm run universal
```

## Platform Support

| Platform | Architecture | libc | Status |
|----------|--------------|------|--------|
| macOS | x64 | - | Supported |
| macOS | ARM64 | - | Supported |
| Linux | x64 | glibc | Supported |
| Linux | x64 | musl | Supported |
| Linux | ARM64 | glibc | Supported |
| Linux | ARM64 | musl | Supported |
| Windows | x64 | MSVC | Supported |
| Windows | ARM64 | MSVC | Supported |

## Performance

The Node.js bindings provide near-native performance by using NAPI-RS to call directly into the Rust implementation. Key performance characteristics:

- **Inference latency**: < 1ms for typical inputs
- **Training throughput**: ~10,000 examples/second (CPU)
- **Memory efficient**: Rust memory management with zero-copy where possible

## Error Handling

All methods that can fail throw JavaScript `Error` objects with descriptive messages:

```typescript
try {
  const result = machine.infer([GroundedInput.text('invalid input')]);
} catch (error) {
  console.error('Inference failed:', error.message);
}
```

## TypeScript Support

Full TypeScript definitions are included. Import types directly:

```typescript
import type {
  NSRConfig,
  TrainingStats,
  EvaluationResult,
  NSRStats
} from '@stateset/nsr';
```

## Related Packages

- **Rust crate**: [`stateset-nsr`]https://crates.io/crates/stateset-nsr - Core Rust implementation
- **Python package**: [`nsr`]https://pypi.org/project/nsr/ - Python bindings

## License

Business Source License 1.1 (BSL-1.1)

The license converts to Apache 2.0 on December 8, 2028.

## Links

- [GitHub Repository]https://github.com/stateset/stateset-nsr
- [Documentation]https://docs.rs/stateset-nsr
- [Issue Tracker]https://github.com/stateset/stateset-nsr/issues
- [StateSet]https://stateset.io

## Contributing

Contributions are welcome! Please see the [contributing guidelines](https://github.com/stateset/stateset-nsr/blob/main/CONTRIBUTING.md) for more information.