npm package: @neutron_me/neural
Description: The hive — memory and intelligence OS for AI agents
Latest version: 0.1.3

# @neutron_me/neural

**The hive** — memory and intelligence OS for AI agents.

Give your AI agents persistent memory across sessions. Neural stores what your agents learn, surfaces relevant context at runtime, and gets smarter with every interaction.

→ [neural.npay.dev](https://neural.npay.dev)

---

## 5-Minute Quick Start

```bash
npm install @neutron_me/neural
```

### Try it instantly — no API key needed

```typescript
import { Neural } from '@neutron_me/neural';

// Works immediately with no setup — runs locally, no network calls
const neural = new Neural();

const memory = await neural.getMemory({ agentId: 'my-agent', userId: 'user-123' });
console.log(memory.block); // Realistic memory block, ready to inject into your prompt
```

Demo mode runs fully locally. No API key, no sign-up, no network requests. Use it to build your integration before connecting to the live hive.

### Get a free API key

```bash
# Step 1 — request a verification code (sent to your email)
curl -X POST https://api-neural.npay.dev/v1/keys/request \
  -H "Content-Type: application/json" \
  -d '{"email":"you@example.com"}'

# Step 2 — verify and get your key
curl -X POST https://api-neural.npay.dev/v1/keys/verify \
  -H "Content-Type: application/json" \
  -d '{"email":"you@example.com","otp":"123456"}'
# → {"apiKey":"nrl_...","tier":"free"}
```

Then connect to the live hive:

```typescript
import { Neural } from '@neutron_me/neural';

const neural = new Neural({ apiKey: 'nrl_your_key_here' });

// 1. Fetch memory before your agent runs
const memory = await neural.getMemory({ agentId: 'support-bot', userId: 'user-123' });

// 2. Inject memory block into your system prompt
const systemPrompt = `You are a helpful assistant.

${memory.block ? `MEMORY:\n${memory.block}` : ''}`;

// 3. Run your agent...
const response = await yourLLM.complete(systemPrompt, userMessage);

// 4. Log the outcome so Neural learns
await neural.log({
  agentId: 'support-bot',
  userId: 'user-123',
  summary: 'User asked about billing. Resolved successfully.',
  facts: ['User is on Pro plan', 'Billing cycle is monthly'],
  outcome: 'success',
  tokensUsed: 1240,
  model: 'claude-opus-4-6',
});
```

---

## LangChain Integration

```typescript
import { Neural } from '@neutron_me/neural';
import { ChatAnthropic } from '@langchain/anthropic';
import { HumanMessage, SystemMessage } from '@langchain/core/messages';

const neural = new Neural({ apiKey: process.env.NEURAL_API_KEY! });
const llm = new ChatAnthropic({ model: 'claude-opus-4-6' });

async function runWithMemory(userId: string, userMessage: string) {
  // Fetch memory
  const memory = await neural.getMemory({ agentId: 'langchain-agent', userId });

  // Build messages with memory context
  const messages = [
    new SystemMessage(`You are a helpful assistant.
    
${memory.block ? `MEMORY FROM PREVIOUS SESSIONS:\n${memory.block}` : 'No previous context.'}`),
    new HumanMessage(userMessage),
  ];

  const response = await llm.invoke(messages);

  // Log back to Neural
  await neural.log({
    agentId: 'langchain-agent',
    userId,
    summary: `User: ${userMessage.slice(0, 100)}. Outcome: success`,
    outcome: 'success',
    model: 'claude-opus-4-6',
  });

  return response.content;
}
```

---

## Express Middleware

Automatically fetch memory before every request and inject it into `req.memory`:

```typescript
import express from 'express';
import { Neural } from '@neutron_me/neural';

const app = express();
const neural = new Neural({ apiKey: process.env.NEURAL_API_KEY! });

// Apply middleware to routes that need memory
app.use('/chat', neural.middleware({
  agentId: 'chat-bot',
  getUserId: (req) => req.user?.id ?? req.headers['x-user-id'] as string,
}));

app.post('/chat', (req, res) => {
  const { block, tier, sessionCount } = req.memory!;
  
  const systemPrompt = block
    ? `You are helpful. Previous context:\n${block}`
    : 'You are helpful.';

  // ... run your LLM
  res.json({ message: 'Response here' });
});
```

---

## API Reference

### `new Neural(config?)`

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `apiKey` | `string` | — | Your Neural API key (`nrl_...`). Omit to run in demo mode (local, no network) |
| `baseUrl` | `string` | `https://api-neural.npay.dev/v1` | API base URL |
| `timeout` | `number` | `3000` | Request timeout in ms |
| `fallback` | `boolean` | `true` | Return empty memory on error (keeps agent running) |

### `neural.getMemory(options): Promise<MemoryResult>`

Fetch the compressed memory block for an agent+user pair.

| Option | Type | Description |
|--------|------|-------------|
| `agentId` | `string` | Your agent identifier |
| `userId` | `string` | The user interacting with the agent |
| `maxChars` | `number?` | Max characters in the returned block |

**Returns:** `{ block: string, tier: string, sessionCount: number, lockedHints: string[] }`

### `neural.log(options): Promise<void>`

Log a session outcome. Neural uses this to build and update memory.

| Option | Type | Description |
|--------|------|-------------|
| `agentId` | `string` | Your agent identifier |
| `userId` | `string` | The user interacting with the agent |
| `summary` | `string` | What happened this session |
| `facts` | `string[]?` | Discrete facts to store |
| `outcome` | `'success'\|'failure'\|'partial'` | Session outcome |
| `tokensUsed` | `number?` | Tokens consumed (for analytics) |
| `model` | `string?` | Model used (for analytics) |

### `neural.createAgent(options): Promise<void>`

Register a new agent with its identity and constraints.

### `neural.updateMemory(options): Promise<void>`

Directly update a specific memory layer (e.g., `priorities`, `identity`, `context`).

### `neural.middleware(options)`

Express middleware that injects `req.memory` before your route handler.

---

## Tier Comparison

| Feature | Free | Pro | Business |
|---------|------|-----|----------|
| Memory | 1,000 chars / 30 days | 14,000 chars / 1 year | 40,000 chars / 3 years |
| Hive contribution | ✅ | ✅ | ✅ |
| Locked hints | ❌ | ✅ | ✅ |
| Priority routing | ❌ | ❌ | ✅ |
| SLA | ❌ | 99.9% | 99.99% |
| Price | Free | $49/mo | $199/mo |

---

## Fallback Behavior

With `fallback: true` (default), any API error returns:

```typescript
{ block: '', tier: 'free', sessionCount: 0, lockedHints: [] }
```

Your agent keeps running without memory rather than crashing. Set `fallback: false` to throw errors instead.

---

→ [neural.npay.dev](https://neural.npay.dev)