nanosolana 0.2.0 → 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/CHANGELOG.md ADDED
@@ -0,0 +1,66 @@
1
+ # Changelog
2
+
3
+ All notable changes to NanoSolana will be documented in this file.
4
+
5
+ ## [1.0.0] — 2025-03-15
6
+
7
+ ### 🎉 First Stable Release
8
+
9
+ NanoSolana hits 1.0! Production-ready autonomous trading agents on Solana.
10
+
11
+ ### ✨ New Features
12
+
13
+ - **`nanosolana demo`** — Zero-config simulation mode. Try the full OODA loop without any API keys.
14
+ - **SDK Examples** — 5 runnable examples: basic agent, custom strategy, webhook alerts, multi-agent mesh, and programmatic SDK usage.
15
+ - **Enhanced npm presence** — 30 discovery keywords, 12+ badges, comparison table, SDK usage docs.
16
+ - **GitHub Actions CI/CD** — Automated testing on Node 22/23, auto-publish on release with npm provenance.
17
+ - **PR & Issue Templates** — Standardized contribution workflow.
18
+ - **GitHub Sponsors** — `FUNDING.yml` for community support.
19
+
20
+ ### 🛡️ Security
21
+
22
+ - AES-256-GCM vault for all secrets
23
+ - HMAC-SHA256 gateway authentication
24
+ - Ed25519 wallet signatures with timing-safe comparison
25
+ - Rate limiting: 10 conn/min, 100 msg/min
26
+
27
+ ### 📦 Package
28
+
29
+ - Proper TypeScript `types` field and conditional exports
30
+ - `publishConfig` for public npm access
31
+ - `prepublishOnly` build step
32
+ - Expanded `files` to include CHANGELOG
33
+
34
+ ### 🏗️ Architecture
35
+
36
+ - OODA Trading Loop (Observe → Orient → Decide → Act → Learn)
37
+ - ClawVault 3-tier epistemological memory (Known/Learned/Inferred)
38
+ - TamaGOchi virtual pet risk modifier
39
+ - Mesh networking via Tailscale VPN
40
+ - On-chain NFT identity via Metaplex (devnet)
41
+ - 40+ channel plugins (Telegram, Discord, Slack, WhatsApp, Nostr...)
42
+ - 50+ composable agent skills
43
+
44
+ ## [0.2.0] — 2025-03-12
45
+
46
+ ### Added
47
+
48
+ - OODA trading engine with Jupiter Ultra Swap
49
+ - ClawVault 3-tier memory with experience replay
50
+ - TamaGOchi pet engine with mood-based risk modification
51
+ - Helius blockchain scanner (DAS API, Enhanced Transactions)
52
+ - On-chain agent registry (Metaplex NFT)
53
+ - Interactive NanoBot web UI
54
+ - Gateway server (WebSocket + HTTP)
55
+ - Tailscale mesh networking
56
+ - 25+ CLI commands
57
+
58
+ ## [0.1.0] — 2025-03-10
59
+
60
+ ### Added
61
+
62
+ - Initial release
63
+ - Solana wallet management
64
+ - Birdeye price feeds
65
+ - Basic trading signals
66
+ - Terminal animations
package/README.md CHANGED
@@ -1,100 +1,253 @@
1
1
  <div align="center">
2
2
 
3
- ```
4
- ███╗ ██╗ █████╗ ███╗ ██╗ ██████╗ ███████╗ ██████╗ ██╗ █████╗ ███╗ ██╗ █████╗
5
- ████╗ ██║██╔══██╗████╗ ██║██╔═══██╗██╔════╝██╔═══██╗██║ ██╔══██╗████╗ ██║██╔══██╗
6
- ██╔██╗ ██║███████║██╔██╗ ██║██║ ██║███████╗██║ ██║██║ ███████║██╔██╗ ██║███████║
7
- ██║╚██╗██║██╔══██║██║╚██╗██║██║ ██║╚════██║██║ ██║██║ ██╔══██║██║╚██╗██║██╔══██║
8
- ██║ ╚████║██║ ██║██║ ╚████║╚██████╔╝███████║╚██████╔╝███████╗██║ ██║██║ ╚████║██║ ██║
9
- ╚═╝ ╚═══╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝
10
- ```
3
+ # 🦞 NanoSolana
4
+
5
+ **Deploy autonomous Solana trading agents in 30 seconds.**
11
6
 
12
- **The Open-Source Agentic Framework for Financial Intelligence on Solana**
7
+ [![npm version](https://img.shields.io/npm/v/nanosolana?color=14F195&style=flat-square)](https://npmjs.com/package/nanosolana)
8
+ [![npm downloads](https://img.shields.io/npm/dm/nanosolana?color=9945FF&style=flat-square)](https://npmjs.com/package/nanosolana)
9
+ [![GitHub stars](https://img.shields.io/github/stars/x402agent/NanoSolana?color=14F195&style=flat-square)](https://github.com/x402agent/NanoSolana)
10
+ [![License: MIT](https://img.shields.io/badge/License-MIT-14F195.svg?style=flat-square)](LICENSE)
11
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.9-3178C6?style=flat-square&logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
12
+ [![Solana](https://img.shields.io/badge/Solana-Native-9945FF?style=flat-square&logo=solana&logoColor=white)](https://solana.com)
13
+ [![Node](https://img.shields.io/badge/Node-%E2%89%A522-339933?style=flat-square&logo=node.js&logoColor=white)](https://nodejs.org)
14
+ [![GitHub last commit](https://img.shields.io/github/last-commit/x402agent/NanoSolana?color=14F195&style=flat-square)](https://github.com/x402agent/NanoSolana)
15
+ [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-14F195?style=flat-square)](https://github.com/x402agent/NanoSolana/blob/main/CONTRIBUTING.md)
16
+ [![Discord](https://img.shields.io/badge/Discord-Join-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/nanosolana)
13
17
 
14
- [![License: MIT](https://img.shields.io/badge/License-MIT-14F195.svg)](LICENSE)
15
- [![Solana](https://img.shields.io/badge/Solana-Native-9945FF.svg)](https://solana.com)
16
- [![npm](https://img.shields.io/npm/v/nanosolana?color=14F195)](https://npmjs.com/package/nanosolana)
18
+ The open-source **agentic framework** for autonomous financial intelligence on Solana.
19
+ OODA trading loops · epistemological memory · mesh coordination · virtual pet soul.
17
20
 
18
- [Website](https://nanosolana.com) · [Hub](https://hub.nanosolana.com) · [Docs](https://docs.nanosolana.com) · [GitHub](https://github.com/x402agent/NanoSolana)
21
+ [Website](https://nanosolana.com) · [Hub](https://hub.nanosolana.com) · [Docs](https://docs.nanosolana.com) · [GitHub](https://github.com/x402agent/NanoSolana) · [Discord](https://discord.gg/nanosolana)
19
22
 
20
23
  </div>
21
24
 
22
- ## One-Shot Deploy
25
+ ---
26
+
27
+ ## ⚡ One Command. Full Agent.
23
28
 
24
29
  ```bash
25
30
  npx nanosolana go
26
31
  ```
27
32
 
28
- That's it one command handles API key setup, wallet creation, blockchain scan, on-chain NFT identity, OODA trading loop, and gateway.
33
+ That's it. One command handles: **API key setup wallet creation blockchain scan on-chain NFT identity OODA trading loop WebSocket gateway.** All secrets encrypted with AES-256-GCM.
34
+
35
+ ```
36
+ ✓ Secrets encrypted → ~/.nanosolana/vault.enc
37
+ ✓ Wallet created: 7xKp...3nYd
38
+ ✓ TamaGOchi hatched: 🥚 NanoAlpha 😊
39
+ ✓ ClawVault online: 0K/0L/0I
40
+ ✓ OODA trading loop active
41
+ ✓ On-chain identity: 5mNt...
42
+ ✓ Gateway: ws://0.0.0.0:18790
43
+
44
+ ══════════════════════════════════════════════════════
45
+ 🦞 NanoAlpha is LIVE. All systems operational.
46
+ ══════════════════════════════════════════════════════
47
+ ```
48
+
49
+ ---
50
+
51
+ ## 🎯 Why NanoSolana?
29
52
 
30
- ## Install
53
+ Other agent frameworks are **built for chat and retrofitted for finance.** NanoSolana is built from the ground up for autonomous financial agents.
54
+
55
+ | Feature | NanoSolana | Eliza | AutoGPT | LangChain |
56
+ |---------|:---------:|:-----:|:-------:|:---------:|
57
+ | Built for finance | ✅ Native | ❌ Chat | ❌ General | ❌ General |
58
+ | Epistemological memory | ✅ 3-tier | ❌ | ❌ | Partial |
59
+ | OODA trading loop | ✅ Military-grade | ❌ | ❌ | ❌ |
60
+ | Encrypted secrets vault | ✅ AES-256-GCM | ❌ .env | ❌ .env | ❌ .env |
61
+ | On-chain identity (NFT) | ✅ Metaplex | ❌ | ❌ | ❌ |
62
+ | Mesh networking | ✅ P2P | ❌ | ❌ | ❌ |
63
+ | Virtual pet risk modifier | ✅ TamaGOchi | ❌ | ❌ | ❌ |
64
+ | One-command deploy | ✅ `npx nanosolana go` | ❌ | ❌ | ❌ |
65
+ | TypeScript-first SDK | ✅ Full types | Partial | Python | Python |
66
+ | Solana-native execution | ✅ Jupiter/Helius | ❌ | ❌ | Plugin |
67
+
68
+ ---
69
+
70
+ ## 📦 Install
31
71
 
32
72
  ```bash
73
+ # Global install
33
74
  npm install -g nanosolana
75
+
76
+ # Or run directly
77
+ npx nanosolana go
78
+
79
+ # Or from source
80
+ git clone https://github.com/x402agent/NanoSolana.git
81
+ cd NanoSolana/nano-core && npm install
82
+ npm run nanosolana -- go
34
83
  ```
35
84
 
36
- Or step-by-step:
85
+ ### Try Without API Keys
37
86
 
38
87
  ```bash
39
- nanosolana init # Configure API keys (encrypted at rest)
40
- nanosolana birth # Create Solana wallet + mint Birth Certificate NFT + blockchain scan
41
- nanosolana run # Start the OODA trading loop
88
+ npx nanosolana demo
89
+ ```
90
+
91
+ Runs a full simulation with synthetic market data — see the OODA loop in action without any API keys.
92
+
93
+ ---
94
+
95
+ ## 🧠 Architecture
96
+
42
97
  ```
98
+ ┌─────────────────────────────────────────────────────────┐
99
+ │ AGENT RUNTIME │
100
+ │ OODA Loop · ClawVault · Strategy Engine │
101
+ ├─────────────────────────────────────────────────────────┤
102
+ │ INFRASTRUCTURE │
103
+ │ Vault · Gateway · Mesh Network · On-Chain ID │
104
+ ├─────────────────────────────────────────────────────────┤
105
+ │ INTERFACES │
106
+ │ CLI · Telegram · Discord · NanoBot UI · Chrome Ext │
107
+ └─────────────────────────────────────────────────────────┘
108
+ ```
109
+
110
+ ```
111
+ nano-core/src/
112
+ ├── ai/ → OpenRouter AI provider (multimodal)
113
+ ├── cli/ → nanosolana CLI (25+ commands)
114
+ ├── config/ → AES-256-GCM encrypted vault & Zod-validated config
115
+ ├── gateway/ → HMAC-SHA256 authenticated WebSocket + HTTP server
116
+ ├── memory/ → ClawVault 3-tier epistemological memory engine
117
+ ├── network/ → Tailscale + tmux mesh networking
118
+ ├── nft/ → Metaplex gasless devnet birth certificate NFT
119
+ ├── onchain/ → Helius blockchain reader (DAS, Enhanced Tx)
120
+ ├── pet/ → TamaGOchi virtual pet engine (mood × risk)
121
+ ├── strategy/ → RSI + EMA + ATR auto-optimizer
122
+ ├── trading/ → OODA trading engine + Jupiter swap execution
123
+ └── wallet/ → Solana Ed25519 wallet manager
124
+ ```
125
+
126
+ ---
127
+
128
+ ## 🔁 The OODA Trading Loop
43
129
 
44
- ## Architecture
130
+ Military-grade decision cycle adapted for autonomous trading:
45
131
 
46
132
  ```
47
- nano-core/
48
- ├── src/
49
- ├── ai/ → OpenRouter AI provider (multimodal: text, image, audio, video)
50
- ├── cli/ → `nanosolana` CLI (25+ commands)
51
- ├── config/ → AES-256-GCM encrypted vault & Zod-validated config
52
- ├── gateway/ → HMAC-SHA256 authenticated WebSocket + HTTP server
53
- ├── hub/ → NanoHub bridge for UI communication
54
- ├── memory/ → ClawVault 3-tier epistemological memory engine
55
- ├── network/ → Tailscale + tmux mesh networking
56
- ├── nft/ → Metaplex gasless devnet birth certificate NFT
57
- │ ├── onchain/ → Helius blockchain reader (DAS, Enhanced Tx, wallet scan)
58
- │ ├── registry/ → On-chain agent identity (Metaplex NFT registration)
59
- │ ├── nanobot/ → Interactive local web UI companion
60
- │ ├── pet/ → TamaGOchi virtual pet engine (mood × risk)
61
- │ ├── strategy/ → RSI + EMA + ATR auto-optimizer
62
- │ ├── telegram/ → Persistent conversation store (200 msg/chat)
63
- │ ├── trading/ → OODA trading engine + Jupiter swap execution
64
- │ └── wallet/ → Solana Ed25519 wallet manager
65
- ├── SOUL.md → Agent identity system prompt
66
- └── extensions/ → 14+ plugins (Telegram, Discord, Nostr, etc.)
133
+ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
134
+ OBSERVE │──▶│ ORIENT │──▶│ DECIDE │──▶│ ACT │
135
+ │ │ │ │ │
136
+ Helius │ │ OpenRouter│ │ Signal │ │ Jupiter │
137
+ Birdeye │ AI Model │ │ Scoring │ │ Swaps │
138
+ └──────────┘ └──────────┘ └──────────┘ └────┬─────┘
139
+
140
+ ┌──────────┐ │
141
+ └──────────────│ LEARN │◀──────────────────┘
142
+ ClawVault
143
+ └──────────┘
67
144
  ```
68
145
 
69
- ## Commands
146
+ 1. **Observe** — Real-time data from Helius RPC + Birdeye API
147
+ 2. **Orient** — AI analysis via OpenRouter (multimodal)
148
+ 3. **Decide** — Structured signals with confidence scoring (≥70% to act)
149
+ 4. **Act** — Jupiter swap execution with slippage protection
150
+ 5. **Learn** — ClawVault experience replay + contradiction detection
151
+
152
+ ---
153
+
154
+ ## 💻 SDK Usage (Programmatic)
155
+
156
+ Use NanoSolana as a library in your own projects:
157
+
158
+ ```typescript
159
+ import {
160
+ NanoWallet,
161
+ TradingEngine,
162
+ ClawVault,
163
+ StrategyEngine,
164
+ TamaGOchi,
165
+ loadConfig,
166
+ } from "nanosolana";
167
+
168
+ // Load encrypted config
169
+ const config = loadConfig();
170
+
171
+ // Create wallet + trading engine
172
+ const wallet = new NanoWallet("my-agent");
173
+ await wallet.birth();
174
+
175
+ const engine = new TradingEngine(config, wallet);
176
+ await engine.start();
177
+
178
+ // Listen for signals
179
+ engine.on("signal", (signal) => {
180
+ console.log(`${signal.type} ${signal.symbol} @ ${signal.confidence * 100}%`);
181
+ });
182
+
183
+ // 3-tier memory
184
+ const vault = new ClawVault();
185
+ vault.storeKnown({
186
+ content: "SOL is at $142.50",
187
+ source: "birdeye",
188
+ tags: ["SOL", "price"],
189
+ });
190
+
191
+ // Virtual pet
192
+ const pet = new TamaGOchi("MyPet");
193
+ console.log(pet.getStatusDisplay());
194
+ ```
195
+
196
+ ---
197
+
198
+ ## 🎮 CLI Commands
70
199
 
71
200
  | Command | Description |
72
201
  |---------|-------------|
73
202
  | `nanosolana go` | **One-shot: init + birth + scan + register + trade** |
203
+ | `nanosolana demo` | **Simulation mode — no API keys needed** |
74
204
  | `nanosolana init` | Configure + encrypt API keys |
75
- | `nanosolana birth` | Create wallet + mint Birth Certificate NFT + blockchain scan |
205
+ | `nanosolana birth` | Create wallet + mint Birth Certificate NFT |
76
206
  | `nanosolana run` | Start OODA trading loop |
77
- | `nanosolana scan [address]` | **Blockchain data scan SOL, tokens, NFTs, tx history** |
78
- | `nanosolana register` | **Mint on-chain agent identity NFT (devnet)** |
79
- | `nanosolana registry` | **Show on-chain agent identity** |
80
- | `nanosolana nanobot` | **Launch interactive NanoBot web UI** |
81
- | `nanosolana dvd` | Floating DVD screensaver 🦞 |
207
+ | `nanosolana scan [addr]` | Blockchain scan (SOL, tokens, NFTs, tx history) |
208
+ | `nanosolana register` | Mint on-chain identity NFT (devnet) |
209
+ | `nanosolana nanobot` | Launch interactive web UI |
210
+ | `nanosolana status` | Agent + wallet + pet status |
211
+ | `nanosolana pet status` | TamaGOchi pet mood & evolution |
212
+ | `nanosolana dvd` | 🦞 DVD screensaver in your terminal |
82
213
  | `nanosolana lobster` | Animated Unicode lobster mascot |
83
- | `nanosolana status` | Show agent + wallet + pet status |
84
- | `nanosolana trade status` | Trading P&L and strategy state |
85
- | `nanosolana trade signals` | Recent trading signals with confidence |
86
- | `nanosolana wallet balance` | SOL + SPL token balances |
87
- | `nanosolana pet status` | TamaGOchi pet mood and evolution |
88
- | `nanosolana memory search` | Search ClawVault memory |
89
- | `nanosolana gateway run` | Start WebSocket gateway |
90
- | `nanosolana channels status` | Check channel connections |
91
- | `nanosolana vault set <key> <val>` | Store encrypted secret |
92
- | `nanosolana send <msg>` | One-shot message to nano bots |
93
- | `nanosolana nodes` | List Tailscale mesh peers |
94
- | `nanosolana doctor` | Run diagnostics |
95
- | `nanosolana security audit` | Full security scan |
96
-
97
- ## Required API Keys
214
+
215
+ ---
216
+
217
+ ## 🐾 TamaGOchi: The Pet That Trades
218
+
219
+ Your agent has a virtual pet whose mood affects risk tolerance:
220
+
221
+ ```
222
+ 🥚 Egg 🐛 Larva 🐣 Juvenile 🦞 Adult → 👑 Alpha → 👻 Ghost
223
+ ```
224
+
225
+ | Mood | Trigger | Risk Effect |
226
+ |------|---------|-------------|
227
+ | 😊 Happy | Recent wins | +10% position |
228
+ | 😐 Content | Normal | No change |
229
+ | 🤤 Hungry | Not fed in 24h | -10% position |
230
+ | 😢 Sad | Recent losses | -15% position |
231
+ | 👻 Ghost | Health = 0 | **Trading disabled** |
232
+
233
+ Neglect your agent → trading de-risks → eventually halts. A dead man's switch by design.
234
+
235
+ ---
236
+
237
+ ## 🔐 Security
238
+
239
+ | Layer | Protection |
240
+ |-------|------------|
241
+ | **Secrets** | AES-256-GCM vault with PBKDF2 |
242
+ | **Gateway** | HMAC-SHA256 on every connection |
243
+ | **Comparison** | `crypto.timingSafeEqual` always |
244
+ | **Rate Limit** | 10 conn/min, 100 msg/min |
245
+ | **Wallet** | Ed25519 key never leaves vault |
246
+ | **Audit** | `nanosolana security audit --deep` |
247
+
248
+ ---
249
+
250
+ ## 🔑 Required API Keys
98
251
 
99
252
  | Key | Source | Required |
100
253
  |-----|--------|----------|
@@ -105,59 +258,51 @@ nano-core/
105
258
  | `BIRDEYE_API_KEY` | [birdeye.so](https://birdeye.so) | Recommended |
106
259
  | `JUPITER_API_KEY` | [jup.ag](https://jup.ag) | For trading |
107
260
 
108
- ## Security
261
+ All keys are **AES-256-GCM encrypted** in the local vault. Never stored in plaintext.
109
262
 
110
- - ✅ AES-256-GCM encrypted secrets vault
111
- - ✅ HMAC-SHA256 gateway authentication
112
- - ✅ Ed25519 wallet signatures
113
- - ✅ Timing-safe token comparison
114
- - ✅ Rate limiting (10 conn/min, 100 msg/min)
115
- - ✅ File permissions enforced (0600/0700)
116
- - ✅ Wallet private key never leaves the vault
263
+ ---
117
264
 
118
- ## Trading Engine (OODA)
119
-
120
- 1. **Observe** — Real-time data from Helius RPC + Birdeye API
121
- 2. **Orient** — AI analysis via OpenRouter (multimodal)
122
- 3. **Decide** — Structured signals with confidence scoring
123
- 4. **Act** — Jupiter swap execution with slippage protection
124
- 5. **Learn** — ClawVault experience replay + contradiction detection
265
+ ## 🌐 Ecosystem
125
266
 
126
- ## Blockchain Intelligence (Helius)
267
+ | Component | Description |
268
+ |-----------|-------------|
269
+ | **nano-core** | TypeScript runtime + CLI (this package) |
270
+ | **NanoHub** | Agent registry & skills marketplace |
271
+ | **Extensions** | 40+ channel plugins (Telegram, Discord, Slack, WhatsApp, Nostr...) |
272
+ | **Chrome Extension** | Manifest V3 browser relay |
273
+ | **TamaGObot** | Ultra-lightweight Go binary (<10MB) |
274
+ | **Skills** | 50+ composable agent skills |
127
275
 
128
- At agent birth, NanoSolana instantly reads the blockchain:
276
+ ---
129
277
 
130
- - **DAS API** — tokens, NFTs, compressed assets
131
- - **Enhanced Transactions** — parsed tx history with descriptions
132
- - **Priority Fees** — real-time fee estimation
133
- - **Wallet Snapshot** — SOL balance, token prices, NFT inventory
278
+ ## 🤝 Contributing
134
279
 
135
- ## On-Chain Identity
280
+ We welcome contributions! See [CONTRIBUTING.md](https://github.com/x402agent/NanoSolana/blob/main/CONTRIBUTING.md).
136
281
 
137
- Every agent mints a **Metaplex NFT** on devnet as its on-chain identity:
282
+ **Areas where we need help:**
138
283
 
139
- - Agent public key
140
- - NanoSolana version
141
- - Registered skills
142
- - SHA-256 fingerprint
284
+ - 🧪 New trading strategies and indicators
285
+ - 🧠 Memory engine improvements (vector search, LanceDB)
286
+ - 📡 New channel plugins (Matrix, Zulip)
287
+ - 🔒 Security audits and hardening
288
+ - 📊 Backtesting framework
289
+ - 📝 Documentation and tutorials
290
+ - 🌐 Internationalization
143
291
 
144
- ## TamaGOchi Pet
292
+ ---
145
293
 
146
- 🥚 Egg → 🐛 Larva → 🐣 Juvenile → 🦞 Adult → 👑 Alpha → 👻 Ghost
294
+ ## 📄 License
147
295
 
148
- Pet mood affects risk tolerance. Feed to keep alive!
296
+ MIT [NanoSolana Labs](https://nanosolana.com)
149
297
 
150
- ## Chrome Extension
298
+ ---
151
299
 
152
- Manifest V3 browser extension for tab relay, wallet management, chat, and manual trades via the gateway.
300
+ <div align="center">
153
301
 
154
- ## Links
302
+ **Built for the financial agents of tomorrow. Open source forever.**
155
303
 
156
- - **Website:** [nanosolana.com](https://nanosolana.com)
157
- - **Hub:** [hub.nanosolana.com](https://hub.nanosolana.com)
158
- - **Docs:** [docs.nanosolana.com](https://docs.nanosolana.com)
159
- - **GitHub:** [github.com/x402agent/NanoSolana](https://github.com/x402agent/NanoSolana)
304
+ [Website](https://nanosolana.com) · [Hub](https://hub.nanosolana.com) · [Docs](https://docs.nanosolana.com) · [GitHub](https://github.com/x402agent/NanoSolana) · [Discord](https://discord.gg/nanosolana)
160
305
 
161
- ## License
306
+ 🦞 *Built with lobster energy by NanoSolana Labs* 🦞
162
307
 
163
- MIT — [NanoSolana Labs](https://nanosolana.com)
308
+ </div>
@@ -0,0 +1,126 @@
1
+ // src/memory/engine.ts
2
+ import { EventEmitter } from "eventemitter3";
3
+ var MemoryEngine = class extends EventEmitter {
4
+ entries = /* @__PURE__ */ new Map();
5
+ lessons = [];
6
+ gcTimer = null;
7
+ decayMs;
8
+ idCounter = 0;
9
+ constructor(temporalDecayHours = 24) {
10
+ super();
11
+ this.decayMs = temporalDecayHours * 60 * 60 * 1e3;
12
+ }
13
+ nextId() {
14
+ this.idCounter += 1;
15
+ return `mem-${Date.now()}-${this.idCounter}`;
16
+ }
17
+ /**
18
+ * Store a new memory entry.
19
+ */
20
+ store(input) {
21
+ const entry = {
22
+ id: this.nextId(),
23
+ content: input.content,
24
+ source: input.source,
25
+ tags: input.tags ?? [],
26
+ confidence: input.confidence ?? 1,
27
+ createdAt: Date.now(),
28
+ expiresAt: Date.now() + this.decayMs
29
+ };
30
+ this.entries.set(entry.id, entry);
31
+ this.emit("entryStored", entry);
32
+ return entry;
33
+ }
34
+ /**
35
+ * Search entries.
36
+ */
37
+ search(query, limit = 10) {
38
+ const q = query.toLowerCase();
39
+ const results = [];
40
+ for (const entry of this.entries.values()) {
41
+ if (entry.content.toLowerCase().includes(q) || entry.tags.some((t) => t.toLowerCase().includes(q))) {
42
+ results.push(entry);
43
+ }
44
+ }
45
+ return results.sort((a, b) => b.confidence - a.confidence).slice(0, limit);
46
+ }
47
+ /**
48
+ * Reinforce a memory (increase its confidence and extend TTL).
49
+ */
50
+ reinforce(id, boost = 0.1) {
51
+ const entry = this.entries.get(id);
52
+ if (!entry) return;
53
+ entry.confidence = Math.min(1, entry.confidence + boost);
54
+ entry.expiresAt = Date.now() + this.decayMs;
55
+ this.emit("memoryReinforced", id, entry.confidence);
56
+ }
57
+ /**
58
+ * Get learned lessons.
59
+ */
60
+ getLessons() {
61
+ return [...this.lessons];
62
+ }
63
+ /**
64
+ * Add a lesson.
65
+ */
66
+ addLesson(input) {
67
+ const lesson = {
68
+ ...input,
69
+ id: `lesson-${Date.now()}-${this.lessons.length}`,
70
+ createdAt: Date.now()
71
+ };
72
+ this.lessons.push(lesson);
73
+ this.emit("lessonLearned", lesson);
74
+ return lesson;
75
+ }
76
+ /**
77
+ * Get memory stats.
78
+ */
79
+ getStats() {
80
+ const bySource = {};
81
+ let totalConfidence = 0;
82
+ for (const entry of this.entries.values()) {
83
+ bySource[entry.source] = (bySource[entry.source] ?? 0) + 1;
84
+ totalConfidence += entry.confidence;
85
+ }
86
+ return {
87
+ total: this.entries.size,
88
+ bySource,
89
+ lessons: this.lessons.length,
90
+ avgConfidence: this.entries.size > 0 ? totalConfidence / this.entries.size : 0
91
+ };
92
+ }
93
+ /**
94
+ * Garbage collection — remove expired entries.
95
+ */
96
+ gc() {
97
+ const now = Date.now();
98
+ for (const [id, entry] of this.entries) {
99
+ if (entry.expiresAt <= now) {
100
+ this.entries.delete(id);
101
+ this.emit("entryExpired", entry);
102
+ }
103
+ }
104
+ }
105
+ /**
106
+ * Start autonomous GC.
107
+ */
108
+ startAutonomous() {
109
+ if (this.gcTimer) return;
110
+ this.gcTimer = setInterval(() => this.gc(), 5 * 60 * 1e3);
111
+ }
112
+ /**
113
+ * Stop autonomous GC.
114
+ */
115
+ stopAutonomous() {
116
+ if (this.gcTimer) {
117
+ clearInterval(this.gcTimer);
118
+ this.gcTimer = null;
119
+ }
120
+ }
121
+ };
122
+
123
+ export {
124
+ MemoryEngine
125
+ };
126
+ //# sourceMappingURL=chunk-DLA5H4VJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/memory/engine.ts"],"sourcesContent":["/**\n * Nano Solana — Legacy Memory Engine\n *\n * Generic memory engine kept for backward compatibility.\n * New code should use ClawVault (3-tier epistemological memory).\n */\n\nimport { EventEmitter } from \"eventemitter3\";\n\n// ── Types ────────────────────────────────────────────────────\n\nexport interface MemoryEntry {\n id: string;\n content: string;\n source: string;\n tags: string[];\n confidence: number;\n createdAt: number;\n expiresAt: number;\n}\n\nexport interface Lesson {\n id: string;\n pattern: string;\n outcome: string;\n adjustment: string;\n confidenceImpact: number;\n createdAt: number;\n}\n\nexport interface MemoryEngineEvents {\n entryStored: (entry: MemoryEntry) => void;\n entryExpired: (entry: MemoryEntry) => void;\n lessonLearned: (lesson: Lesson) => void;\n memoryReinforced: (id: string, confidence: number) => void;\n}\n\n// ── Memory Engine ────────────────────────────────────────────\n\nexport class MemoryEngine extends EventEmitter<MemoryEngineEvents> {\n private entries: Map<string, MemoryEntry> = new Map();\n private lessons: Lesson[] = [];\n private gcTimer: ReturnType<typeof setInterval> | null = null;\n private decayMs: number;\n private idCounter = 0;\n\n constructor(temporalDecayHours = 24) {\n super();\n this.decayMs = temporalDecayHours * 60 * 60 * 1000;\n }\n\n private nextId(): string {\n this.idCounter += 1;\n return `mem-${Date.now()}-${this.idCounter}`;\n }\n\n /**\n * Store a new memory entry.\n */\n store(input: {\n content: string;\n source: string;\n tags?: string[];\n confidence?: number;\n metadata?: Record<string, unknown>;\n }): MemoryEntry {\n const entry: MemoryEntry = {\n id: this.nextId(),\n content: input.content,\n source: input.source,\n tags: input.tags ?? [],\n confidence: input.confidence ?? 1.0,\n createdAt: Date.now(),\n expiresAt: Date.now() + this.decayMs,\n };\n this.entries.set(entry.id, entry);\n this.emit(\"entryStored\", entry);\n return entry;\n }\n\n /**\n * Search entries.\n */\n search(query: string, limit = 10): MemoryEntry[] {\n const q = query.toLowerCase();\n const results: MemoryEntry[] = [];\n\n for (const entry of this.entries.values()) {\n if (\n entry.content.toLowerCase().includes(q) ||\n entry.tags.some((t) => t.toLowerCase().includes(q))\n ) {\n results.push(entry);\n }\n }\n\n return results\n .sort((a, b) => b.confidence - a.confidence)\n .slice(0, limit);\n }\n\n /**\n * Reinforce a memory (increase its confidence and extend TTL).\n */\n reinforce(id: string, boost = 0.1): void {\n const entry = this.entries.get(id);\n if (!entry) return;\n\n entry.confidence = Math.min(1.0, entry.confidence + boost);\n entry.expiresAt = Date.now() + this.decayMs;\n this.emit(\"memoryReinforced\", id, entry.confidence);\n }\n\n /**\n * Get learned lessons.\n */\n getLessons(): Lesson[] {\n return [...this.lessons];\n }\n\n /**\n * Add a lesson.\n */\n addLesson(input: Omit<Lesson, \"id\" | \"createdAt\">): Lesson {\n const lesson: Lesson = {\n ...input,\n id: `lesson-${Date.now()}-${this.lessons.length}`,\n createdAt: Date.now(),\n };\n this.lessons.push(lesson);\n this.emit(\"lessonLearned\", lesson);\n return lesson;\n }\n\n /**\n * Get memory stats.\n */\n getStats(): {\n total: number;\n bySource: Record<string, number>;\n lessons: number;\n avgConfidence: number;\n } {\n const bySource: Record<string, number> = {};\n let totalConfidence = 0;\n\n for (const entry of this.entries.values()) {\n bySource[entry.source] = (bySource[entry.source] ?? 0) + 1;\n totalConfidence += entry.confidence;\n }\n\n return {\n total: this.entries.size,\n bySource,\n lessons: this.lessons.length,\n avgConfidence: this.entries.size > 0 ? totalConfidence / this.entries.size : 0,\n };\n }\n\n /**\n * Garbage collection — remove expired entries.\n */\n private gc(): void {\n const now = Date.now();\n for (const [id, entry] of this.entries) {\n if (entry.expiresAt <= now) {\n this.entries.delete(id);\n this.emit(\"entryExpired\", entry);\n }\n }\n }\n\n /**\n * Start autonomous GC.\n */\n startAutonomous(): void {\n if (this.gcTimer) return;\n this.gcTimer = setInterval(() => this.gc(), 5 * 60 * 1000);\n }\n\n /**\n * Stop autonomous GC.\n */\n stopAutonomous(): void {\n if (this.gcTimer) {\n clearInterval(this.gcTimer);\n this.gcTimer = null;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