toon-memory 1.8.0 → 2.1.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 +158 -20
- package/dist/cli/capture.js +276 -0
- package/dist/cli/session-start.js +192 -0
- package/dist/cli/setup.js +123 -21
- package/dist/cli/toon-memory.js +3 -2
- package/mcp/server.js +614 -63
- package/package.json +5 -3
- package/skills/toon-memory.md +44 -10
- package/src/cli/capture.ts +187 -0
- package/src/cli/session-start.ts +70 -0
- package/src/cli/setup.ts +148 -15
- package/src/lib/lock.ts +120 -0
- package/src/lib/sessions.ts +225 -0
- package/src/mcp/server.ts +518 -63
- package/src/memory.ts +1 -1
package/README.md
CHANGED
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
- [Quick Start](#quick-start)
|
|
18
18
|
- [Supported Agents](#supported-agents)
|
|
19
19
|
- [MCP Tools](#mcp-tools)
|
|
20
|
+
- [Coordinación multi-sesión](#coordinación-multi-sesión)
|
|
20
21
|
- [Tips & Best Practices](#tips--best-practices)
|
|
21
22
|
- [CLI Commands](#cli-commands)
|
|
22
23
|
- [Configuration](#configuration)
|
|
@@ -59,18 +60,23 @@ Read [How toon-memory Makes Your AI Agent Smarter](https://luiggival08.github.io
|
|
|
59
60
|
|
|
60
61
|
## Features
|
|
61
62
|
|
|
62
|
-
- **
|
|
63
|
+
- **13 MCP tools** — Full memory management via Model Context Protocol, including `memory_sessions` for multi-session coordination
|
|
64
|
+
- **MCP Resources** — Read memory as context without tool invocations
|
|
63
65
|
- **15 agents supported** — OpenCode, VS Code, Claude Code, Cursor, Windsurf, Cline, Continue, Codex CLI, Gemini CLI, Zed, Antigravity, Aider, KiloCode, OpenClaw, Kiro
|
|
64
66
|
- **Interactive installer** — Select which agents to configure from a menu
|
|
65
67
|
- **SessionStart hooks** — Auto-reminders for Claude Code, Codex CLI, Gemini CLI, Antigravity
|
|
66
|
-
- **TOON format** —
|
|
68
|
+
- **TOON format** — 22% fewer tokens than JSON (measured), better LLM comprehension
|
|
67
69
|
- **Per-project memory** — Each project gets its own memory file
|
|
68
70
|
- **Zero config** — Just install and use
|
|
69
71
|
- **Auto gitignore** — Automatically adds `.toon-memory/memory/` to `.gitignore`
|
|
70
72
|
- **Date filtering** — Search memory by date range
|
|
71
|
-
- **Auto-archive** — Old entries (>30 days) or 100+ entries moved to archive automatically
|
|
73
|
+
- **Auto-archive** — Old entries (>30 days), expired TTL entries, or 100+ entries moved to archive automatically
|
|
72
74
|
- **Encryption** — AES-256-GCM encryption for sensitive data
|
|
73
75
|
- **Watch mode** — Auto-backup every N minutes
|
|
76
|
+
- **Memory TTL** — Configurable per-entry expiration (7d, 30d, or exact dates)
|
|
77
|
+
- **Tag inference** — Auto-detect tags from content when tags are empty
|
|
78
|
+
- **Memory diff** — See what changed since your last session
|
|
79
|
+
- **Related entries** — Auto-suggest related memories when saving
|
|
74
80
|
|
|
75
81
|
---
|
|
76
82
|
|
|
@@ -145,14 +151,29 @@ memory_remember # Save important decisions
|
|
|
145
151
|
|
|
146
152
|
| Tool | Description |
|
|
147
153
|
|------|-------------|
|
|
148
|
-
| `memory_remember` | Save a decision, pattern, bug, or knowledge |
|
|
149
|
-
| `memory_recall` | Search memory (use BEFORE reading files) |
|
|
154
|
+
| `memory_remember` | Save a decision, pattern, bug, or knowledge (with optional TTL and auto-tag inference) |
|
|
155
|
+
| `memory_recall` | Search memory (use BEFORE reading files, filters expired TTL entries) |
|
|
150
156
|
| `memory_forget` | Remove an entry by key or id |
|
|
151
|
-
| `memory_stats` | View memory state |
|
|
157
|
+
| `memory_stats` | View memory state (including TTL stats) |
|
|
152
158
|
| `memory_summary` | Save/retrieve file summaries |
|
|
153
|
-
| `memory_archive` | Archive old entries (>30 days) |
|
|
159
|
+
| `memory_archive` | Archive old entries (>30 days) and expired TTL entries |
|
|
160
|
+
| `memory_diff` | Show changes since a date (24h, 7d, or exact date) |
|
|
161
|
+
| `memory_suggest` | Find related entries for a given context |
|
|
154
162
|
| `memory_encrypt` | Enable AES-256-GCM encryption |
|
|
155
163
|
| `memory_decrypt` | Disable encryption |
|
|
164
|
+
| `memory_captured` | List activity auto-captured by hooks (opt-in) or clear the log |
|
|
165
|
+
| `memory_consolidate` | De-duplicate entries with identical content (deterministic, no LLM) |
|
|
166
|
+
| `memory_sessions` | Show active agent sessions (branch, files, last-seen) and soft conflicts for parallel work |
|
|
167
|
+
|
|
168
|
+
### MCP Resources
|
|
169
|
+
|
|
170
|
+
Memory is also exposed as MCP resources for direct context reading:
|
|
171
|
+
|
|
172
|
+
| Resource | URI | Description |
|
|
173
|
+
|----------|-----|-------------|
|
|
174
|
+
| Memory Entries | `toon://memory/entries` | Full memory dump |
|
|
175
|
+
| Memory Stats | `toon://memory/stats` | Category counts and TTL info |
|
|
176
|
+
| Memory Summaries | `toon://memory/summaries` | File summaries
|
|
156
177
|
|
|
157
178
|
### Examples
|
|
158
179
|
|
|
@@ -167,10 +188,42 @@ memory_remember({
|
|
|
167
188
|
tags: "validation;types"
|
|
168
189
|
})
|
|
169
190
|
// 🧠 Guardado: decision/use-zod (a1b2c3d4)
|
|
191
|
+
// 🔗 Entradas relacionadas:
|
|
192
|
+
// [pattern] zod-schemas — Shared Zod schemas for API validation
|
|
170
193
|
```
|
|
171
194
|
|
|
172
195
|
> **Tip:** Use descriptive keys like `use-zod` instead of vague ones like `validation`. Your agent searches by key and content, so specificity helps.
|
|
173
196
|
|
|
197
|
+
#### Remember with TTL
|
|
198
|
+
|
|
199
|
+
```typescript
|
|
200
|
+
memory_remember({
|
|
201
|
+
category: "knowledge",
|
|
202
|
+
key: "sprint-deadline",
|
|
203
|
+
content: "Sprint ends July 18, feature freeze is July 16",
|
|
204
|
+
ttl: "7d"
|
|
205
|
+
})
|
|
206
|
+
// 🧠 Guardado: knowledge/sprint-deadline (x1y2z3w4)
|
|
207
|
+
// ⏰ TTL: 2026-07-19
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
> **Tip:** Use TTL for temporary context like deadlines, sprint info, or time-sensitive notes. Entries with expired TTL are automatically filtered from search results.
|
|
211
|
+
|
|
212
|
+
#### Auto-inferred tags
|
|
213
|
+
|
|
214
|
+
```typescript
|
|
215
|
+
memory_remember({
|
|
216
|
+
category: "bug",
|
|
217
|
+
key: "redis-connection-timeout",
|
|
218
|
+
content: "Redis connection timeout in production, increased pool size"
|
|
219
|
+
// tags left empty — auto-inferred from content
|
|
220
|
+
})
|
|
221
|
+
// 🧠 Guardado: bug/redis-connection-timeout (a1b2c3d4)
|
|
222
|
+
// 🏷️ Tags inferidos: redis
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
> **Tip:** Leave `tags` empty and the system will infer them from your content using a vocabulary of 20+ categories (redis, auth, api, db, security, etc.).
|
|
226
|
+
|
|
174
227
|
#### Search memory
|
|
175
228
|
|
|
176
229
|
```typescript
|
|
@@ -202,7 +255,39 @@ memory_archive()
|
|
|
202
255
|
// 📋 Quedan 42 entradas activas
|
|
203
256
|
```
|
|
204
257
|
|
|
205
|
-
> **Tip:** Run this periodically to keep memory lean. Archived entries are still searchable via `memory_recall` with date filters.
|
|
258
|
+
> **Tip:** Run this periodically to keep memory lean. Archived entries are still searchable via `memory_recall` with date filters. Entries with expired TTL are also archived automatically.
|
|
259
|
+
|
|
260
|
+
#### Show changes since last session
|
|
261
|
+
|
|
262
|
+
```typescript
|
|
263
|
+
memory_diff({ since: "24h" })
|
|
264
|
+
// 📋 Cambios desde 2026-07-11:
|
|
265
|
+
//
|
|
266
|
+
// ➕ Nuevas (2):
|
|
267
|
+
// [decision] use-zod (a1b2c3d4)
|
|
268
|
+
// Use Zod for validation
|
|
269
|
+
// [bug] redis-timeout (e5f6g7h8)
|
|
270
|
+
// Redis connection timeout fix
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
> **Tip:** Use `memory_diff` at the start of a session to see what your agent learned since you last worked on the project.
|
|
274
|
+
|
|
275
|
+
#### Find related entries
|
|
276
|
+
|
|
277
|
+
```typescript
|
|
278
|
+
memory_suggest({ context: "redis cache configuration" })
|
|
279
|
+
// 🔍 Sugerencias para "redis cache configuration":
|
|
280
|
+
//
|
|
281
|
+
// [decision] redis-cache-config (a1b2c3d4)
|
|
282
|
+
// Redis cache layer for session storage
|
|
283
|
+
// File: src/cache.ts | Tags: redis;cache | Date: 2026-07-10
|
|
284
|
+
//
|
|
285
|
+
// [bug] redis-pool-fix (i9j0k1l2)
|
|
286
|
+
// Added max_connections=20
|
|
287
|
+
// File: redis.ts | Tags: redis;fix | Date: 2026-07-10
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
> **Tip:** Use `memory_suggest` when you need context about a topic but aren't sure what to search for.
|
|
206
291
|
|
|
207
292
|
#### Enable encryption
|
|
208
293
|
|
|
@@ -217,6 +302,58 @@ memory_encrypt()
|
|
|
217
302
|
|
|
218
303
|
---
|
|
219
304
|
|
|
305
|
+
## Coordinación multi-sesión
|
|
306
|
+
|
|
307
|
+
When you run **several AI agent sessions in parallel** (e.g. three OpenCode sessions on the same repo at once), they can accidentally clobber each other's work. toon-memory ships with **`memory_sessions`**, a file-based coordination tool that lets every session see what its siblings are doing — with **no server, no network, and no LLM calls**.
|
|
308
|
+
|
|
309
|
+
### How it works
|
|
310
|
+
|
|
311
|
+
- On startup, a `SessionStart` hook writes a **heartbeat file** for the session at `.toon-memory/memory/sessions/<id>.json`. Each process writes *only its own* file, so there's no lock contention.
|
|
312
|
+
- The heartbeat records the agent name, the **git branch**, the **files touched**, and a **last-seen** timestamp.
|
|
313
|
+
- Reading across all those files gives every session a shared, eventually-consistent view of who else is active.
|
|
314
|
+
- Dead sessions (process PID no longer alive **and** a stale heartbeat past the TTL window) are pruned lazily.
|
|
315
|
+
|
|
316
|
+
### The `memory_sessions` tool
|
|
317
|
+
|
|
318
|
+
```typescript
|
|
319
|
+
memory_sessions({ conflictsOnly: false })
|
|
320
|
+
// 🧭 Sesiones activas (2) — ventana 30 min:
|
|
321
|
+
//
|
|
322
|
+
// • opencode @ feature/auth (tú)
|
|
323
|
+
// id: a1b2c3d4
|
|
324
|
+
// hace 2 min
|
|
325
|
+
// Archivos:
|
|
326
|
+
// • src/auth.ts
|
|
327
|
+
//
|
|
328
|
+
// • claude @ feature/db
|
|
329
|
+
// id: e5f6g7h8
|
|
330
|
+
// hace 9 min
|
|
331
|
+
// • src/db.ts
|
|
332
|
+
//
|
|
333
|
+
// 🔥 Conflictos suaves (1):
|
|
334
|
+
// ⚠️ src/types.ts ↔ opencode @ feature/auth, claude @ feature/db
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
- Pass `conflictsOnly: true` to skip the session list and show only soft conflicts:
|
|
338
|
+
```typescript
|
|
339
|
+
memory_sessions({ conflictsOnly: true })
|
|
340
|
+
// 🔥 Conflictos suaves (1):
|
|
341
|
+
//
|
|
342
|
+
// ⚠️ src/types.ts
|
|
343
|
+
// ↔ opencode @ feature/auth (a1b2c3d4), claude @ feature/db (e5f6g7h8)
|
|
344
|
+
```
|
|
345
|
+
- A **soft conflict** is any file touched by 2+ active sessions — a heads-up that you might be editing the same code. It's not a hard lock, just a warning to coordinate.
|
|
346
|
+
|
|
347
|
+
### Recommended parallel-session habit
|
|
348
|
+
|
|
349
|
+
1. At the start of every session, the `SessionStart` hook already prints the other active sessions and any soft conflicts.
|
|
350
|
+
2. Run `memory_sessions()` to see the full picture (branches, files, last-seen) and `memory_sessions({ conflictsOnly: true })` if you only care about clashes.
|
|
351
|
+
3. If you share a file with another session, sync up before editing so you don't overwrite each other's changes.
|
|
352
|
+
|
|
353
|
+
> **Tip:** This is purely local and lock-free — safe to run as often as you like. Combine it with `memory_recall({ query: "project context" })` at session start for both cross-session *memory* and cross-session *presence*.
|
|
354
|
+
|
|
355
|
+
---
|
|
356
|
+
|
|
220
357
|
## Tips & Best Practices
|
|
221
358
|
|
|
222
359
|
Here are some patterns that work well with toon-memory:
|
|
@@ -479,7 +616,7 @@ Add to `~/.config/zed/settings.json`:
|
|
|
479
616
|
## How It Works
|
|
480
617
|
|
|
481
618
|
1. **MCP Server** — Runs locally, talks to your agent via stdio
|
|
482
|
-
2. **TOON Format** — Stores data in Token-Oriented Object Notation (~
|
|
619
|
+
2. **TOON Format** — Stores data in Token-Oriented Object Notation (~22.5% fewer tokens than JSON, measured over 16 entries with gpt-tokenizer)
|
|
483
620
|
3. **Per-project memory** — Each project gets `.toon-memory/memory/data.toon`
|
|
484
621
|
4. **Zero config** — Just install and use
|
|
485
622
|
|
|
@@ -487,10 +624,10 @@ Add to `~/.config/zed/settings.json`:
|
|
|
487
624
|
|
|
488
625
|
```
|
|
489
626
|
version: 1
|
|
490
|
-
entries[3|]{id|category|key|content|file|tags|date}:
|
|
491
|
-
a1b2c3d4|decision|use-zod|Use Zod for validation|src/types.ts|validation;types|2026-07-10
|
|
492
|
-
e5f6g7h8|pattern|pydantic-configs|Project uses Pydantic v2|config.py|python;patterns|2026-07-10
|
|
493
|
-
i9j0k1l2|bug|redis-pool-fix|Added max_connections=20|redis.ts|redis;fix|2026-07-10
|
|
627
|
+
entries[3|]{id|category|key|content|file|tags|date|ttl}:
|
|
628
|
+
a1b2c3d4|decision|use-zod|Use Zod for validation|src/types.ts|validation;types|2026-07-10|
|
|
629
|
+
e5f6g7h8|pattern|pydantic-configs|Project uses Pydantic v2|config.py|python;patterns|2026-07-10|
|
|
630
|
+
i9j0k1l2|bug|redis-pool-fix|Added max_connections=20|redis.ts|redis;fix|2026-07-10|7d
|
|
494
631
|
summaries:
|
|
495
632
|
src/services/redis.ts: Redis connection pool with retry logic
|
|
496
633
|
```
|
|
@@ -519,13 +656,14 @@ summaries:
|
|
|
519
656
|
|
|
520
657
|
TOON (Token-Oriented Object Notation) is designed for LLMs:
|
|
521
658
|
|
|
522
|
-
| Format |
|
|
523
|
-
|
|
524
|
-
| JSON |
|
|
525
|
-
|
|
|
526
|
-
|
|
659
|
+
| Format | Tokens (16 entries) |
|
|
660
|
+
|--------|---------------------|
|
|
661
|
+
| JSON | 1097 |
|
|
662
|
+
| **TOON** | **850** |
|
|
663
|
+
|
|
664
|
+
Measured with `gpt-tokenizer` (cl100k_base) over 16 representative memory entries — see `scripts/benchmark-toon.mjs` (`npm run bench`).
|
|
527
665
|
|
|
528
|
-
- **
|
|
666
|
+
- **22.5% fewer tokens** than JSON at file level (up to 30.5% on a single entry)
|
|
529
667
|
- **Lossless roundtrip** — No data loss
|
|
530
668
|
- **Better LLM comprehension** — Structured for AI consumption
|
|
531
669
|
|
|
@@ -622,7 +760,7 @@ toon-memory/
|
|
|
622
760
|
│ │ ├── setup.ts # CLI commands
|
|
623
761
|
│ │ └── toon-memory.ts # CLI runner
|
|
624
762
|
│ ├── mcp/
|
|
625
|
-
│ │ └── server.ts # MCP server (
|
|
763
|
+
│ │ └── server.ts # MCP server (11 tools + 3 resources)
|
|
626
764
|
│ └── memory.ts # Custom tool (OpenCode)
|
|
627
765
|
├── tests/
|
|
628
766
|
│ ├── cli.test.ts # CLI tests
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
// src/cli/capture.ts
|
|
2
|
+
import { readFileSync as readFileSync3, existsSync as existsSync3, mkdirSync as mkdirSync2 } from "fs";
|
|
3
|
+
import { join as join2 } from "path";
|
|
4
|
+
import { createHash } from "crypto";
|
|
5
|
+
|
|
6
|
+
// src/lib/lock.ts
|
|
7
|
+
import { openSync, closeSync, writeFileSync, readFileSync, unlinkSync, existsSync, statSync, renameSync } from "fs";
|
|
8
|
+
var STALE_MS = 15e3;
|
|
9
|
+
var LOCK_TIMEOUT_MS = 1e4;
|
|
10
|
+
function isAlive(pid) {
|
|
11
|
+
if (!pid || pid <= 0) return false;
|
|
12
|
+
try {
|
|
13
|
+
process.kill(pid, 0);
|
|
14
|
+
return true;
|
|
15
|
+
} catch {
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function tryAcquire(lockFile) {
|
|
20
|
+
if (existsSync(lockFile)) {
|
|
21
|
+
const age = Date.now() - statSync(lockFile).mtimeMs;
|
|
22
|
+
let stale = age > STALE_MS;
|
|
23
|
+
if (!stale) {
|
|
24
|
+
try {
|
|
25
|
+
const pid = parseInt(readFileSync(lockFile, "utf-8").trim(), 10);
|
|
26
|
+
if (!isAlive(pid)) stale = true;
|
|
27
|
+
} catch {
|
|
28
|
+
stale = true;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (stale) {
|
|
32
|
+
try {
|
|
33
|
+
unlinkSync(lockFile);
|
|
34
|
+
} catch {
|
|
35
|
+
}
|
|
36
|
+
} else {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
try {
|
|
41
|
+
const fd = openSync(lockFile, "wx");
|
|
42
|
+
writeFileSync(fd, String(process.pid));
|
|
43
|
+
closeSync(fd);
|
|
44
|
+
return true;
|
|
45
|
+
} catch {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
var held = /* @__PURE__ */ new Map();
|
|
50
|
+
function withLockSync(file, fn) {
|
|
51
|
+
const lockFile = `${file}.lock`;
|
|
52
|
+
const depth = held.get(lockFile) ?? 0;
|
|
53
|
+
if (depth > 0) {
|
|
54
|
+
held.set(lockFile, depth + 1);
|
|
55
|
+
try {
|
|
56
|
+
fn();
|
|
57
|
+
} finally {
|
|
58
|
+
const d = (held.get(lockFile) ?? 0) - 1;
|
|
59
|
+
if (d <= 0) held.delete(lockFile);
|
|
60
|
+
else held.set(lockFile, d);
|
|
61
|
+
}
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
const deadline = Date.now() + LOCK_TIMEOUT_MS;
|
|
65
|
+
while (!tryAcquire(lockFile)) {
|
|
66
|
+
if (Date.now() > deadline) throw new Error(`toon-memory lock timeout: ${file}`);
|
|
67
|
+
const t = Date.now() + 10;
|
|
68
|
+
while (Date.now() < t) {
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
held.set(lockFile, 1);
|
|
72
|
+
try {
|
|
73
|
+
fn();
|
|
74
|
+
} finally {
|
|
75
|
+
const d = (held.get(lockFile) ?? 0) - 1;
|
|
76
|
+
if (d <= 0) {
|
|
77
|
+
held.delete(lockFile);
|
|
78
|
+
try {
|
|
79
|
+
unlinkSync(lockFile);
|
|
80
|
+
} catch {
|
|
81
|
+
}
|
|
82
|
+
} else {
|
|
83
|
+
held.set(lockFile, d);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function atomicWrite(file, content) {
|
|
88
|
+
const tmp = `${file}.tmp`;
|
|
89
|
+
writeFileSync(tmp, content);
|
|
90
|
+
renameSync(tmp, file);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// src/lib/sessions.ts
|
|
94
|
+
import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2, readdirSync, unlinkSync as unlinkSync2 } from "fs";
|
|
95
|
+
import { join } from "path";
|
|
96
|
+
import { execSync } from "child_process";
|
|
97
|
+
var SESSION_TTL_MS = 10 * 60 * 1e3;
|
|
98
|
+
var PRUNE_STALE_MS = 10 * 60 * 1e3;
|
|
99
|
+
function sessionDir() {
|
|
100
|
+
return join(process.cwd(), ".toon-memory", "memory", "sessions");
|
|
101
|
+
}
|
|
102
|
+
function sessionPath(id) {
|
|
103
|
+
return join(sessionDir(), `${id}.json`);
|
|
104
|
+
}
|
|
105
|
+
function ensureSessionDir() {
|
|
106
|
+
const dir = sessionDir();
|
|
107
|
+
if (!existsSync2(dir)) mkdirSync(dir, { recursive: true });
|
|
108
|
+
}
|
|
109
|
+
function resolveSessionId(payload = {}) {
|
|
110
|
+
const fromPayload = payload.session_id || payload.sessionId || payload.session_id_untruncated;
|
|
111
|
+
if (fromPayload && fromPayload.trim()) return fromPayload.trim();
|
|
112
|
+
if (process.env.TOON_MEMORY_SESSION_ID && process.env.TOON_MEMORY_SESSION_ID.trim()) {
|
|
113
|
+
return process.env.TOON_MEMORY_SESSION_ID.trim();
|
|
114
|
+
}
|
|
115
|
+
return `proc-${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
|
|
116
|
+
}
|
|
117
|
+
function currentBranch() {
|
|
118
|
+
if (process.env.TOON_MEMORY_BRANCH && process.env.TOON_MEMORY_BRANCH.trim()) {
|
|
119
|
+
return process.env.TOON_MEMORY_BRANCH.trim();
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
const branch = execSync("git rev-parse --abbrev-ref HEAD", {
|
|
123
|
+
encoding: "utf-8",
|
|
124
|
+
timeout: 2e3,
|
|
125
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
126
|
+
}).trim();
|
|
127
|
+
return branch || "unknown";
|
|
128
|
+
} catch {
|
|
129
|
+
return "unknown";
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
function readRecord(id) {
|
|
133
|
+
const p = sessionPath(id);
|
|
134
|
+
if (!existsSync2(p)) return null;
|
|
135
|
+
try {
|
|
136
|
+
return JSON.parse(readFileSync2(p, "utf-8"));
|
|
137
|
+
} catch {
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
function heartbeat(agent, sessionId, opts = {}) {
|
|
142
|
+
ensureSessionDir();
|
|
143
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
144
|
+
const existing = readRecord(sessionId);
|
|
145
|
+
const record = existing ? { ...existing, agent, pid: process.pid, lastSeen: now, branch: currentBranch(), ended: opts.ended ?? existing.ended } : {
|
|
146
|
+
id: sessionId,
|
|
147
|
+
agent,
|
|
148
|
+
pid: process.pid,
|
|
149
|
+
branch: currentBranch(),
|
|
150
|
+
startedAt: now,
|
|
151
|
+
lastSeen: now,
|
|
152
|
+
ended: opts.ended ?? false,
|
|
153
|
+
files: {}
|
|
154
|
+
};
|
|
155
|
+
if (opts.file && opts.file.trim()) {
|
|
156
|
+
record.files[opts.file.trim()] = now;
|
|
157
|
+
}
|
|
158
|
+
writeFileSync2(sessionPath(sessionId), JSON.stringify(record, null, 2));
|
|
159
|
+
}
|
|
160
|
+
function endSession(agent, sessionId) {
|
|
161
|
+
heartbeat(agent, sessionId, { ended: true });
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// src/cli/capture.ts
|
|
165
|
+
var MEMORY_DIR = join2(process.cwd(), ".toon-memory", "memory");
|
|
166
|
+
var OBSERVATIONS_FILE = join2(MEMORY_DIR, "observations.toon");
|
|
167
|
+
var CONFIG_FILE = join2(MEMORY_DIR, "config.json");
|
|
168
|
+
var DEDUP_WINDOW_MS = 5 * 60 * 1e3;
|
|
169
|
+
function captureEnabled() {
|
|
170
|
+
if (process.env.TOON_MEMORY_CAPTURE) return true;
|
|
171
|
+
try {
|
|
172
|
+
const cfg = JSON.parse(readFileSync3(CONFIG_FILE, "utf-8"));
|
|
173
|
+
if (cfg && cfg.capture) return true;
|
|
174
|
+
} catch {
|
|
175
|
+
}
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
function sessionEnabled() {
|
|
179
|
+
return !process.env.TOON_MEMORY_NO_SESSION;
|
|
180
|
+
}
|
|
181
|
+
function stripSecrets(text) {
|
|
182
|
+
let t = text;
|
|
183
|
+
t = t.replace(/sk-[A-Za-z0-9]{20,}/g, "<redacted>");
|
|
184
|
+
t = t.replace(/AKIA[0-9A-Z]{16}/g, "<redacted>");
|
|
185
|
+
t = t.replace(/gh[pousr]_[A-Za-z0-9]{36,}/g, "<redacted>");
|
|
186
|
+
t = t.replace(/xox[baprs]-[A-Za-z0-9-]{10,}/g, "<redacted>");
|
|
187
|
+
t = t.replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, "<redacted>");
|
|
188
|
+
t = t.replace(/Bearer\s+[A-Za-z0-9._-]+/gi, "Bearer <redacted>");
|
|
189
|
+
t = t.replace(
|
|
190
|
+
/(password|secret|token|api[_-]?key|access[_-]?key|private[_-]?key)\s*[:=]\s*["']?[A-Za-z0-9/+._-]{8,}/gi,
|
|
191
|
+
(m) => m.replace(/[A-Za-z0-9/+._-]{8,}$/, "<redacted>")
|
|
192
|
+
);
|
|
193
|
+
return t;
|
|
194
|
+
}
|
|
195
|
+
function derive(tool, input) {
|
|
196
|
+
let file = "";
|
|
197
|
+
let summary = "";
|
|
198
|
+
if (input && typeof input === "object") {
|
|
199
|
+
const obj = input;
|
|
200
|
+
file = String(obj.file_path || obj.path || obj.filename || obj.notebook_path || "");
|
|
201
|
+
const rawCmd = obj.command ?? obj.cmd ?? obj.prompt ?? obj.new_string ?? obj.old_string ?? obj.content ?? "";
|
|
202
|
+
if (rawCmd) summary = String(rawCmd);
|
|
203
|
+
else summary = JSON.stringify(obj).slice(0, 200);
|
|
204
|
+
} else if (typeof input === "string") {
|
|
205
|
+
summary = input;
|
|
206
|
+
}
|
|
207
|
+
summary = stripSecrets(String(summary || "")).replace(/\s+/g, " ").trim().slice(0, 200);
|
|
208
|
+
return { file: String(file || "").trim(), summary };
|
|
209
|
+
}
|
|
210
|
+
function ensureMemoryDir() {
|
|
211
|
+
if (!existsSync3(MEMORY_DIR)) mkdirSync2(MEMORY_DIR, { recursive: true });
|
|
212
|
+
}
|
|
213
|
+
function appendObservation(row) {
|
|
214
|
+
ensureMemoryDir();
|
|
215
|
+
let data = existsSync3(OBSERVATIONS_FILE) ? readFileSync3(OBSERVATIONS_FILE, "utf-8") : "version: 1\nobservations[0|]{ts|session|agent|branch|tool|hash|file|summary}:\n";
|
|
216
|
+
const lines = data.split("\n");
|
|
217
|
+
let headerIdx = lines.findIndex((l) => l.startsWith("observations["));
|
|
218
|
+
if (headerIdx === -1) {
|
|
219
|
+
lines.push("observations[0|]{ts|session|agent|branch|tool|hash|file|summary}:");
|
|
220
|
+
headerIdx = lines.length - 1;
|
|
221
|
+
}
|
|
222
|
+
const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0).map((l) => l.trim());
|
|
223
|
+
entryLines.unshift(row);
|
|
224
|
+
const match = lines[headerIdx].match(/\[(\d+)\|/);
|
|
225
|
+
const count = match ? parseInt(match[1]) : 0;
|
|
226
|
+
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`);
|
|
227
|
+
lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...entryLines.map((l) => ` ${l}`));
|
|
228
|
+
withLockSync(OBSERVATIONS_FILE, () => atomicWrite(OBSERVATIONS_FILE, lines.join("\n")));
|
|
229
|
+
}
|
|
230
|
+
function main() {
|
|
231
|
+
const agent = process.argv[2] || "agent";
|
|
232
|
+
let raw = "";
|
|
233
|
+
try {
|
|
234
|
+
raw = readFileSync3(0, "utf-8");
|
|
235
|
+
} catch {
|
|
236
|
+
process.exit(0);
|
|
237
|
+
}
|
|
238
|
+
let payload = {};
|
|
239
|
+
try {
|
|
240
|
+
payload = JSON.parse(raw);
|
|
241
|
+
} catch {
|
|
242
|
+
process.exit(0);
|
|
243
|
+
}
|
|
244
|
+
const toolName = payload.tool_name || payload.toolName || payload.tool || "";
|
|
245
|
+
const isStop = !toolName && (payload.session_id || payload.stop_reason || payload.session_id_untruncated);
|
|
246
|
+
const effectiveTool = toolName || "Stop";
|
|
247
|
+
const sessionId = resolveSessionId(payload);
|
|
248
|
+
if (sessionEnabled()) {
|
|
249
|
+
const input2 = payload.tool_input ?? payload.input ?? {};
|
|
250
|
+
const { file: file2 } = derive(effectiveTool, input2);
|
|
251
|
+
if (isStop) endSession(agent, sessionId);
|
|
252
|
+
else heartbeat(agent, sessionId, { file: file2 });
|
|
253
|
+
}
|
|
254
|
+
if (!captureEnabled()) process.exit(0);
|
|
255
|
+
const input = payload.tool_input ?? payload.input ?? {};
|
|
256
|
+
const { file, summary } = derive(effectiveTool, input);
|
|
257
|
+
const normalized = JSON.stringify(input ?? {});
|
|
258
|
+
const hash = createHash("sha256").update(`${effectiveTool}|${normalized}`).digest("hex").slice(0, 16);
|
|
259
|
+
const ts = (/* @__PURE__ */ new Date()).toISOString();
|
|
260
|
+
const branch = currentBranch();
|
|
261
|
+
if (existsSync3(OBSERVATIONS_FILE)) {
|
|
262
|
+
const data = readFileSync3(OBSERVATIONS_FILE, "utf-8");
|
|
263
|
+
for (const line of data.split("\n")) {
|
|
264
|
+
if (!line.startsWith(" ")) continue;
|
|
265
|
+
const p = line.trim().split("|");
|
|
266
|
+
if (p[5] === hash) {
|
|
267
|
+
const prev = new Date(p[0]).getTime();
|
|
268
|
+
if (Date.now() - prev < DEDUP_WINDOW_MS) process.exit(0);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
if (!isStop && !toolName) process.exit(0);
|
|
273
|
+
appendObservation(`${ts}|${sessionId}|${agent}|${branch}|${effectiveTool}|${hash}|${file}|${summary}`);
|
|
274
|
+
process.exit(0);
|
|
275
|
+
}
|
|
276
|
+
main();
|