midstream 0.2.0

Real-time LLM streaming with inflight analysis
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
# MidStream CLI

[![npm version](https://img.shields.io/npm/v/midstream-cli.svg)](https://www.npmjs.com/package/midstream-cli)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.3-blue.svg)](https://www.typescriptlang.org/)
[![WASM](https://img.shields.io/badge/WebAssembly-Enabled-blueviolet.svg)](https://webassembly.org/)
[![MCP](https://img.shields.io/badge/MCP-Compatible-green.svg)](https://modelcontextprotocol.io/)

**Real-time LLM Streaming with Lean Agentic Learning**

Created by [ruv.io]https://ruv.io | [@ruvnet]https://github.com/ruvnet

---

## ๐ŸŒŸ Introduction

**MidStream** is a cutting-edge CLI and MCP (Model Context Protocol) server that brings state-of-the-art autonomous agent capabilities to LLM streaming. Unlike traditional systems that process data after completion, MidStream analyzes, learns, and adapts **in real-time** as data flows through.

### What Makes MidStream Special?

- **Inflight Learning**: Learns from streaming data as it arrives, not after
- **Temporal Intelligence**: Detects patterns and predicts next steps in conversations
- **Meta-Learning**: Improves how it learns, creating a self-optimizing system
- **Formal Verification**: Ensures safety and correctness using temporal logic
- **Ultra-Fast**: WebAssembly-powered with <1ms latency on critical operations

## โœจ Features

### ๐Ÿš€ Core Capabilities

**Temporal Analysis**
- Dynamic Time Warping (DTW) for sequence similarity
- Longest Common Subsequence (LCS) for pattern matching
- Edit distance calculation for measuring differences
- Automatic pattern detection in conversation flows

**Real-Time Scheduling**
- Earliest Deadline First (EDF) scheduling
- Rate-Monotonic scheduling
- Priority-based task execution
- Nanosecond-precision timing

**Behavior Analysis**
- Strange attractor detection
- Chaos/stability monitoring via Lyapunov exponents
- Phase space reconstruction
- Predictive behavior modeling

**Formal Verification**
- Linear Temporal Logic (LTL) verification
- Metric Temporal Logic (MTL) with time bounds
- Neural-symbolic reasoning
- Automated counterexample generation

**Meta-Learning**
- 4-level meta-learning hierarchy
- Strange loop detection
- Self-referential reasoning
- Safe self-modification with safety constraints

### ๐Ÿ“ก Streaming Protocols

- **WebSocket**: Full-duplex real-time communication
- **SSE (Server-Sent Events)**: Unidirectional server push
- **HTTP Streaming**: Compatible with standard HTTP clients

### ๐Ÿ”ง MCP Integration

Full Model Context Protocol support enables:
- Seamless integration with MCP-compatible LLM tools
- Standard tool interface for conversation analysis
- Real-time pattern detection and prediction
- Temporal sequence comparison

## ๐ŸŽฏ Benefits

### For Developers

โœ… **Drop-in Integration**: Works with existing LLM pipelines
โœ… **Language Agnostic**: WASM bindings work in any JavaScript environment
โœ… **Production Ready**: Comprehensive tests and benchmarks
โœ… **Well Documented**: Extensive API docs and examples

### For AI Applications

๐Ÿง  **Smarter Agents**: Meta-learning enables continuous improvement
โšก **Ultra-Responsive**: <10ms analysis latency for real-time applications
๐Ÿ›ก๏ธ **Safety First**: Formal verification ensures correct behavior
๐Ÿ“Š **Deep Insights**: Temporal analysis reveals hidden patterns

### For Research

๐Ÿ”ฌ **State-of-the-Art**: Implements latest research in temporal logic and dynamical systems
๐Ÿ“ˆ **Reproducible**: Comprehensive benchmarking and testing framework
๐Ÿ”“ **Open Source**: Full access to implementation details

## ๐ŸŒ Unique Position

MidStream is the **only** open-source solution that combines:

1. **Lean Agentic Programming**: Formal reasoning + autonomous agents
2. **Real-Time Streaming Analysis**: Process data inflight, not in batch
3. **Temporal Intelligence**: DTW, LCS, and pattern matching for sequences
4. **Dynamical Systems Theory**: Chaos detection and stability analysis
5. **Meta-Learning**: Multi-level learning hierarchy with strange loops
6. **WASM Performance**: Native speed in any JavaScript environment
7. **MCP Compatibility**: Standard protocol for LLM tool integration

### Competitive Comparison

| Feature | MidStream | Traditional Agents | LangChain | AutoGPT |
|---------|-----------|-------------------|-----------|---------|
| Real-time Learning | โœ… | โŒ | โŒ | โŒ |
| Temporal Analysis | โœ… | โŒ | โŒ | โŒ |
| Meta-Learning | โœ… | โŒ | โŒ | โŒ |
| Formal Verification | โœ… | โŒ | โŒ | โŒ |
| WASM Performance | โœ… | โŒ | โŒ | โŒ |
| MCP Support | โœ… | โŒ | โš ๏ธ | โŒ |
| Streaming Protocols | 3 | 0-1 | 0-1 | 0 |

## ๐Ÿš€ Quick Start

### Installation

```bash
npm install -g midstream-cli
```

### CLI Usage

#### Process a Message

```bash
midstream process "Hello, how can I analyze patterns?"
```

#### Analyze a Conversation

```bash
midstream analyze examples/conversation1.json
```

#### Compare Two Sequences

```bash
midstream compare examples/sequence1.json examples/sequence2.json --algorithm dtw
```

#### Start Streaming Servers

```bash
midstream serve --ws-port 3001 --sse-port 3002
```

This starts both WebSocket and SSE servers:
- WebSocket: `ws://localhost:3001`
- SSE: `http://localhost:3002`

#### Interactive Mode

```bash
midstream interactive
```

Provides a menu-driven interface for all operations.

#### Run Benchmarks

```bash
midstream benchmark --size 100 --iterations 1000
```

### MCP Server

Start the MCP server for integration with MCP-compatible tools:

```bash
midstream mcp
```

Or use npm script:

```bash
npm run mcp
```

The MCP server provides these tools:
- `analyze_conversation` - Analyze conversation patterns
- `compare_sequences` - Compare temporal sequences
- `detect_patterns` - Find pattern occurrences
- `analyze_behavior` - Detect chaos/stability
- `meta_learn` - Perform meta-learning
- `get_status` - Get agent status
- `stream_websocket` - Start WebSocket server
- `stream_sse` - Start SSE server

## ๐Ÿ“š Usage Examples

### Node.js/TypeScript Integration

```typescript
import { MidStreamAgent } from 'midstream-cli';

// Create agent
const agent = new MidStreamAgent({
  maxHistory: 1000,
  embeddingDim: 3,
});

// Process streaming messages
const result = agent.processMessage("What's the weather?");

// Analyze conversation
const analysis = agent.analyzeConversation([
  "Hello",
  "What's the weather?",
  "It's sunny and 72ยฐF",
  "Perfect, thank you!"
]);

console.log('Pattern detection:', analysis.patterns);
console.log('Meta-learning insights:', analysis.metaLearning);

// Compare sequences
const similarity = agent.compareSequences(
  ["greeting", "weather", "response"],
  ["greeting", "weather", "location", "response"],
  "dtw"
);

console.log('Sequence similarity:', similarity);

// Analyze behavior
const behaviorAnalysis = agent.analyzeBehavior([
  0.8, 0.82, 0.79, 0.81, 0.80
]);

console.log('Is stable:', behaviorAnalysis.isStable);
console.log('Is chaotic:', behaviorAnalysis.isChaotic);
```

### WebSocket Client

```typescript
import { WebSocket } from 'ws';

const ws = new WebSocket('ws://localhost:3001');

ws.on('open', () => {
  // Send a message for processing
  ws.send(JSON.stringify({
    type: 'process',
    payload: {
      message: 'Hello, MidStream!'
    }
  }));
});

ws.on('message', (data) => {
  const response = JSON.parse(data.toString());
  console.log('Received:', response);
});
```

### SSE Client

```typescript
const EventSource = require('eventsource');

const es = new EventSource('http://localhost:3002/stream');

es.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('SSE Update:', data);
};

// Send data via HTTP POST
fetch('http://localhost:3002/process', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ message: 'Hello!' })
});
```

### Browser Usage

```html
<!DOCTYPE html>
<html>
<head>
  <title>MidStream WASM Demo</title>
</head>
<body>
  <script type="module">
    import init, { MidStreamAgent } from './midstream_wasm.js';

    async function main() {
      await init();

      const agent = new MidStreamAgent({
        maxHistory: 100,
        embeddingDim: 3,
      });

      const result = agent.process_message("Hello!");
      console.log(result);
    }

    main();
  </script>
</body>
</html>
```

## ๐Ÿ”ง Configuration

### Agent Configuration

```typescript
const config = {
  maxHistory: 1000,        // Maximum conversation history
  embeddingDim: 3,         // Embedding dimension for attractor analysis
  schedulingPolicy: 'EDF', // EDF, RM, Priority, or FIFO
};

const agent = new MidStreamAgent(config);
```

### Server Configuration

```bash
# WebSocket server on custom port
midstream serve --ws-port 8080

# SSE server on custom port
midstream serve --sse-port 8081

# Both servers
midstream serve --ws-port 8080 --sse-port 8081
```

## ๐Ÿงช Testing

```bash
# Run all tests
npm test

# Run with coverage
npm run test:coverage

# Watch mode
npm run test:watch
```

## ๐Ÿ“Š Benchmarks

Run performance benchmarks:

```bash
midstream benchmark --size 100 --iterations 1000
```

Expected performance (on modern hardware):
- DTW (n=100): <10ms
- LCS (n=100): <5ms
- Pattern Detection: <50ms
- Meta-Learning: <5ms per event
- WebSocket Latency: <1ms

## ๐Ÿ› ๏ธ Development

### Build from Source

```bash
# Clone repository
git clone https://github.com/ruvnet/midstream
cd midstream/npm

# Install dependencies
npm install

# Build WASM bindings
npm run build:wasm

# Build TypeScript
npm run build:ts

# Run tests
npm test
```

### Project Structure

```
npm/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ agent.ts          # Agent wrapper
โ”‚   โ”œโ”€โ”€ cli.ts            # CLI implementation
โ”‚   โ”œโ”€โ”€ mcp-server.ts     # MCP server
โ”‚   โ”œโ”€โ”€ streaming.ts      # WebSocket & SSE servers
โ”‚   โ””โ”€โ”€ __tests__/        # Test files
โ”œโ”€โ”€ examples/             # Example data files
โ”œโ”€โ”€ wasm/                 # Built WASM bindings
โ””โ”€โ”€ dist/                 # Built JavaScript
```

## ๐Ÿ“– API Documentation

### MidStreamAgent

**Constructor**
```typescript
new MidStreamAgent(config?: AgentConfig)
```

**Methods**
- `processMessage(message: string)` - Process single message
- `analyzeConversation(messages: string[])` - Analyze conversation
- `compareSequences(seq1, seq2, algorithm)` - Compare sequences
- `detectPattern(sequence, pattern)` - Find pattern occurrences
- `analyzeBehavior(rewards: number[])` - Analyze behavior stability
- `learn(content: string, reward: number)` - Meta-learning
- `getStatus()` - Get agent status
- `reset()` - Clear all history

### Streaming Servers

**WebSocketStreamServer**
```typescript
const server = new WebSocketStreamServer(port);
await server.start();
```

**SSEStreamServer**
```typescript
const server = new SSEStreamServer(port);
await server.start();
```

## ๐Ÿค Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

## ๐Ÿ“„ License

MIT License - see [LICENSE](LICENSE) file for details.

## ๐Ÿ”— Links

- **GitHub**: https://github.com/ruvnet/midstream
- **npm Package**: https://www.npmjs.com/package/midstream-cli
- **Documentation**: https://docs.midstream.dev
- **Discord**: https://discord.gg/midstream
- **Created by**: [ruv.io]https://ruv.io | [@ruvnet]https://github.com/ruvnet

## ๐Ÿ™ Acknowledgments

Built on cutting-edge research in:
- Temporal Logic (Pnueli 1977)
- Dynamical Systems Theory (Strogatz 2015)
- Strange Loops (Hofstadter 1979)
- Meta-Learning (Finn et al. 2017)
- Real-Time Scheduling (Liu & Layland 1973)

## ๐Ÿ“ˆ Roadmap

- [ ] GPU acceleration for large-scale DTW
- [ ] Distributed processing support
- [ ] Advanced temporal logic operators
- [ ] QUIC protocol support
- [ ] Browser extension for LLM analysis
- [ ] Visual dashboard for real-time monitoring

## ๐Ÿ’ฌ Support

- GitHub Issues: https://github.com/ruvnet/midstream/issues
- Discord Community: https://discord.gg/midstream
- Email: support@ruv.io

---

**Made with โค๏ธ by the MidStream Team**

*Empowering the next generation of intelligent agents*