Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat: release version 1.0.0 with SQLite-backed Second Brain memory, enhanced CLI streaming, and Telegram message filtering.
Salman Qureshi531f47d1b899
diff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 00000000..97ecaef4--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,75 @@+# Changelog++## 1.0.0 — Second Brain++This is a **major release** because it introduces the Second Brain — a persistent, structured memory system backed by SQLite with full-text search — alongside fundamental changes to how Mercury stores data and renders output.++### Why 1.0.0?++Mercury has been in rapid development through 0.x releases. The Second Brain feature represents a fundamental capability shift: Mercury now **remembers** across conversations, automatically extracting, consolidating, and recalling facts about you. Combined with the all-in-`~/.mercury/` data architecture and live CLI streaming, this marks a stable, production-ready foundation warranting a major version.++### Second Brain 🧠++- **10 memory types** — identity, preference, goal, project, habit, decision, constraint, relationship, episode, reflection+- **Automatic extraction** — after each conversation, Mercury extracts 0–3 facts with confidence, importance, and durability scores+- **Relevant recall** — before each message, injects top 5 matching memories within a 900-character budget+- **Auto-consolidation** — every 60 minutes, synthesizes a profile summary, active-state summary, and generates reflection memories from detected patterns+- **Conflict resolution** — opposing memories resolved by higher confidence or recency; negation detection handles "likes X" vs "does not like X"+- **Active → Durable promotion** — memories reinforced 3+ times automatically promote from short-lived `active` scope to long-lived `durable` scope+- **Auto-pruning** — active-scope memories stale after 21 days; inferred memories decay; low-confidence durable memories dismissed after 120 days+- **SQLite + FTS5** — full-text search for instant recall, all data stored locally at `~/.mercury/memory/second-brain/second-brain.db`+- **User controls** — `/memory` for overview, search, pause, resume, and clear in both CLI and Telegram++### CLI Streaming Restored++- **Live text streaming** — raw response tokens stream to the terminal as they arrive, then the full response is re-rendered with proper markdown formatting (headings in cyan with `■` markers, code blocks in yellow, lists with dim bullets, blockquotes with dim borders)+- **Cursor save/restore** — uses `\x1b7`/`\x1b8` ANSI sequences instead of fragile line counting, eliminating the duplicate-response bug for single-line answers+- **Tool feedback during streaming** — tool calls appear inline during streaming and are tracked for accurate output replacement++### Data Architecture: All in `~/.mercury/`++- **Before**: Memory (short-term, long-term, episodic) was stored relative to CWD at `./memory/`, creating files in random project directories+- **After**: All state now lives under `~/.mercury/` — config, soul, memory, permissions, skills, schedules, token tracking, daemon state+- **`getMemoryDir()`** helper returns `~/.mercury/memory/` — no more `memory.dir` config field+- **Auto-migration** — on first run, Mercury detects and moves any legacy `./memory/` directory to `~/.mercury/memory/`, then removes the old directory+- **Removed config fields**: `memory.dir`, `memory.secondBrain.dbPath` — these are now computed from `getMercuryHome()`++### Permission Modes++- **Ask Me** — confirm before file writes, shell commands that need approval, and scope changes (default on both CLI and Telegram)+- **Allow All** — auto-approve everything for the session (scopes, commands, loop continuation). Resets on restart.+- CLI: arrow-key menu at session start. Telegram: inline keyboard on first message, `/permissions` to change.++### Step-by-Step Tool Feedback++- **Numbered steps** — each tool call gets a step number (`1. read_file foo.ts`)+- **Spinner** — animated spinner with elapsed time while tools execute+- **Result summaries** — concise result shown after each step (e.g., `42 lines, 3 matches`)++### Other Changes++- **Improved markdown renderer** — cyan headings with `■` markers, yellow inline code, dim strikethrough, blue underlined links with dim URLs, bordered blockquotes, bordered tables+- **HTML entity decoding** — fixes double-encoding from marked's HTML output+- **Telegram organization access** — admins and members with approve/reject/promote/demote flows+- **Model selection during onboarding** — after validating an API key, Mercury fetches available models and lets you choose+- **Telegram editable status messages** — streaming updates use `editMessageText` for live response editing+- **Scheduled task notifications** — Mercury notifies the originating channel when a scheduled task runs+- **Full temporary scope for scheduled tasks** — tasks run in Allow All mode with auto-approved scopes++### Breaking Changes++- Memory data paths changed from `./memory/` to `~/.mercury/memory/` — auto-migration handles this+- Config field `memory.dir` removed — no action needed, value is ignored+- Config field `memory.secondBrain.dbPath` removed — path is now computed automatically++### Full Changelog++**0.5.4** — Fix streaming alignment, remove agent name duplication, cleaner block format+**0.5.3** — Add mercury upgrade command, ENOTEMPTY fix+**0.5.2** — Fix readline prompt handling, streaming re-render, interactive loop detection, HTML entity decoding+**0.5.1** — Bug fixes+**0.5.0** — Telegram organization access, model selection, updated docs+**0.4.0** — Social media skills, GitHub companion+**0.3.0** — Permission system, skill system, scheduler+**0.2.0** — Telegram streaming, file uploads, daemon mode+**0.1.0** — Initial release\ No newline at end of filediff --git a/README.md b/README.mdindex a0a789cb..9e66a3ea 100644--- a/README.md+++ b/README.md@@ -7,7 +7,7 @@</p><p align="center">- Runs 24/7 from CLI or Telegram. 31 built-in tools. Extensible skills. Asks before it acts.+ Remembers what matters. Asks before it acts. Runs 24/7 from CLI or Telegram. 31 built-in tools, extensible skills, SQLite-backed Second Brain memory.</p><p align="center">@@ -41,12 +41,13 @@ mercury doctor## Why Mercury?-Every AI agent can read files, run commands, and fetch URLs. Most do it silently. **Mercury asks first.**+Every AI agent can read files, run commands, and fetch URLs. Most do it silently. **Mercury asks first — and remembers what matters.**-- **Permission-hardened** — Shell blocklist (`sudo`, `rm -rf /`, etc. never execute). Folder-level read/write scoping. Pending approval flow. Skill elevation with granular `allowed-tools`. No surprises.+- **Permission-hardened** — Shell blocklist (`sudo`, `rm -rf /`, etc. never execute). Folder-level read/write scoping. Pending approval flow. Ask Me or Allow All per session. No surprises.+- **Second Brain** — Persistent, structured memory with SQLite + FTS5 full-text search. 10 memory types, auto-extraction, conflict resolution, auto-consolidation. Mercury learns your preferences, goals, and habits without manual entry.- **Soul-driven** — Personality defined by markdown files you own (`soul.md`, `persona.md`, `taste.md`, `heartbeat.md`). No corporate wrapper.- **Token-aware** — Daily budget enforcement. Auto-concise when over 70%. `/budget` command to check, reset, or override.-- **Multi-channel** — CLI with real-time streaming. Telegram with HTML formatting, file uploads, and typing indicators.+- **Live streaming** — Real-time token streaming on CLI with cursor-save/restore and markdown re-rendering. Telegram streaming with editable status messages.- **Always on** — Run as a background daemon on any OS. Auto-restarts on crash. Starts on boot. Cron scheduling, heartbeat monitoring, and proactive notifications.- **Extensible** — Install community skills with a single command. Schedule skills as recurring tasks. Based on the [Agent Skills](https://agentskills.io) specification.@@ -161,8 +162,8 @@ Type these during a conversation — they don't consume API tokens. Work on both| Channel | Features ||---------|----------|-| **CLI** | Readline prompt, arrow-key command menus, real-time text streaming, markdown rendering, permission mode picker |-| **Telegram** | HTML formatting, file uploads, typing indicators, multi-user access with admin/member roles, editable status messages |+| **CLI** | Readline prompt, arrow-key command menus, real-time text streaming with markdown re-rendering, permission mode picker |+| **Telegram** | HTML formatting, editable streaming messages, file uploads, typing indicators, multi-user access with admin/member roles |### Telegram Access@@ -196,7 +197,7 @@ Mercury builds a structured, persistent memory that grows with every conversatio- **User controls** — `/memory` for overview, search, pause, resume, and clear- **Disable** — `SECOND_BRAIN_ENABLED=false` env var or `memory.secondBrain.enabled: false` in config-All data stays on your machine in `~/.mercury/memory/second-brain/second-brain.db` (SQLite + FTS5).+All data stays on your machine in `~/.mercury/memory/second-brain/second-brain.db` (SQLite + FTS5). No cloud.## Configuration@@ -211,8 +212,10 @@ All runtime data lives in `~/.mercury/` — not in your project directory.| `~/.mercury/skills/` | Installed skills || `~/.mercury/schedules.yaml` | Scheduled tasks || `~/.mercury/token-usage.json` | Daily token usage tracking |-| `~/.mercury/memory/` | Short-term, long-term, episodic memory |-| `~/.mercury/memory/second-brain.db` | SQLite database for structured long-term memory (FTS5) |+| `~/.mercury/memory/short-term/` | Per-conversation JSON files |+| `~/.mercury/memory/long-term/` | Auto-extracted facts (JSONL) |+| `~/.mercury/memory/episodic/` | Timestamped event log (JSONL) |+| `~/.mercury/memory/second-brain/` | Structured memory database (SQLite + FTS5) || `~/.mercury/daemon.pid` | Background process PID || `~/.mercury/daemon.log` | Daemon mode logs |@@ -237,8 +240,9 @@ When a provider fails, Mercury automatically tries the next one. It remembers th- **TypeScript + Node.js 18+** — ESM, tsup build- **Vercel AI SDK v4** — `generateText` + `streamText`, 10-step agentic loop, provider fallback-- **grammY** — Telegram bot with typing indicators and file uploads-- **SQLite + JSONL** — Second brain (SQLite with FTS5), short/long-term/episodic memory (JSONL)+- **grammY** — Telegram bot with typing indicators, editable streaming, and file uploads+- **SQLite + FTS5** — Second brain with full-text search, conflict resolution, auto-consolidation+- **JSONL** — Short-term, long-term, and episodic conversation memory- **Daemon manager** — Background spawn + PID file + watchdog crash recovery- **System services** — macOS LaunchAgent, Linux systemd, Windows Task Schedulerdiff --git a/docs/index.html b/docs/index.htmlindex 2fdf98a7..d558a7fc 100644--- a/docs/index.html+++ b/docs/index.html@@ -172,7 +172,8 @@<section id="second-brain" class="section section-alt"><div class="container"><h2 class="section-title">🧠 Second Brain</h2>- <p class="section-subtitle">Mercury doesn't just chat — it <em>remembers</em>. A persistent, structured memory that grows with every conversation.</p>+ <p class="section-subtitle">Most AI agents forget everything when you close the chat. Mercury <em>remembers</em> — automatically, privately, and with surgical precision.</p>+<div class="brain-grid"><div class="brain-card" data-reveal><h3>Learns Automatically</h3>@@ -196,11 +197,46 @@</div><div class="brain-card" data-reveal><h3>You Stay in Control</h3>- <p><code>/memory</code> gives you overview, search, pause, and clear. Second Brain can be disabled entirely via config. All data stays on your machine in SQLite.</p>+ <p><code>/memory</code> gives you overview, search, pause, and clear. Second Brain can be disabled entirely via config. All data stays on your machine in SQLite — nothing leaves your machine.</p></div></div>++ <div class="brain-architecture" data-reveal>+ <h3>How It Works</h3>+ <div class="brain-flow">+ <div class="brain-step">+ <div class="brain-step-num">1</div>+ <div class="brain-step-content">+ <strong>Extract</strong>+ <p>After every conversation, a dedicated extraction pass pulls 0–3 facts. Each fact gets a type, confidence score (0–1), importance, and durability rating. Below 0.55 confidence? Rejected.</p>+ </div>+ </div>+ <div class="brain-step">+ <div class="brain-step-num">2</div>+ <div class="brain-step-content">+ <strong>Store & Merge</strong>+ <p>Facts land in SQLite with FTS5 full-text search. If a similar fact already exists, Mercury merges — incrementing evidence count, updating confidence, and resolving contradictions. No duplicates.</p>+ </div>+ </div>+ <div class="brain-step">+ <div class="brain-step-num">3</div>+ <div class="brain-step-content">+ <strong>Recall</strong>+ <p>Before each message, a FTS5 query retrieves the top 5 relevant memories within a 900-character budget. Only what matters enters context. Your token spend stays low.</p>+ </div>+ </div>+ <div class="brain-step">+ <div class="brain-step-num">4</div>+ <div class="brain-step-content">+ <strong>Consolidate & Prune</strong>+ <p>Every 60 minutes: profile synthesis, reflection generation, and active→durable promotion (3+ evidence). Auto-pruning dismisses stale active memories (21 days) and decays low-confidence durables (120 days).</p>+ </div>+ </div>+ </div>+ </div>+<div class="brain-note" data-reveal>- <p>Enable/disable: <code>SECOND_BRAIN_ENABLED=false</code> env var or <code>memory.secondBrain.enabled: false</code> in <code>~/.mercury/mercury.yaml</code>. Enabled by default.</p>+ <p><strong>Why it matters:</strong> This isn't a chat history dump. It's a structured knowledge graph that improves with every conversation — the more you use Mercury, the better it gets. And because it uses SQLite + FTS5 on your local machine, recall is instant, search is sub-millisecond, and your data never leaves <code>~/.mercury/</code>. Enable/disable: <code>SECOND_BRAIN_ENABLED=false</code> env var or <code>memory.secondBrain.enabled: false</code> in <code>~/.mercury/mercury.yaml</code>. Enabled by default.</p></div></div></section>diff --git a/docs/style.css b/docs/style.cssindex fe882864..75e46d3e 100644--- a/docs/style.css+++ b/docs/style.css@@ -624,4 +624,80 @@ footer {.brain-card h3 { font-size: 1.15em; margin-bottom: 8px; color: var(--white); }.brain-card p { color: var(--gray); font-size: 0.95em; line-height: 1.65; }.brain-note { margin-top: 32px; text-align: center; color: var(--gray-dim); font-size: 0.88em; }-.brain-note code { background: var(--bg-card); border: 1px solid var(--border); padding: 2px 6px; border-radius: 4px; font-size: 0.85em; color: var(--cyan); }\ No newline at end of file+.brain-note code { background: var(--bg-card); border: 1px solid var(--border); padding: 2px 6px; border-radius: 4px; font-size: 0.85em; color: var(--cyan); }++/* ── Second Brain Architecture Flow ── */+.brain-architecture {+ margin-top: 56px;+ padding: 40px 36px;+ background: var(--bg-card);+ border: 1px solid var(--border);+ border-radius: 16px;+}+.brain-architecture h3 {+ font-size: 1.3em;+ color: var(--white);+ margin-bottom: 32px;+ text-align: center;+}+.brain-flow {+ display: flex;+ flex-direction: column;+ gap: 0;+ position: relative;+}+.brain-flow::before {+ content: '';+ position: absolute;+ left: 28px;+ top: 32px;+ bottom: 32px;+ width: 2px;+ background: linear-gradient(to bottom, var(--cyan), var(--cyan-dim), transparent);+}+.brain-step {+ display: flex;+ gap: 20px;+ align-items: flex-start;+ padding: 20px 0;+ position: relative;+}+.brain-step-num {+ flex-shrink: 0;+ width: 56px;+ height: 56px;+ display: flex;+ align-items: center;+ justify-content: center;+ background: linear-gradient(135deg, rgba(0, 212, 255, 0.15), rgba(0, 212, 255, 0.05));+ border: 1px solid var(--cyan-dim);+ border-radius: 50%;+ font-family: var(--font);+ font-size: 1.2em;+ font-weight: 700;+ color: var(--cyan);+ position: relative;+ z-index: 1;+}+.brain-step-content {+ flex: 1;+ padding-top: 4px;+}+.brain-step-content strong {+ display: block;+ font-size: 1.05em;+ color: var(--white);+ margin-bottom: 6px;+}+.brain-step-content p {+ color: var(--gray);+ font-size: 0.92em;+ line-height: 1.65;+ margin: 0;+}++@media (max-width: 640px) {+ .brain-architecture { padding: 24px 16px; }+ .brain-step-num { width: 40px; height: 40px; font-size: 1em; }+ .brain-flow::before { left: 20px; }+}\ No newline at end of filediff --git a/package.json b/package.jsonindex 6812c140..8cf2ba02 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "@cosmicstack/mercury-agent",- "version": "0.5.4",- "description": "Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI or Telegram.",+ "version": "1.0.0",+ "description": "Soul-driven AI agent with Second Brain memory, permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI or Telegram.","type": "module","main": "dist/index.js","bin": {diff --git a/src/channels/telegram.ts b/src/channels/telegram.tsindex 21e92082..dfad4ab3 100644--- a/src/channels/telegram.ts+++ b/src/channels/telegram.ts@@ -267,6 +267,10 @@ export class TelegramChannel extends BaseChannel {const timeSuffix = elapsedMs != null ? `\n⏱ ${(elapsedMs / 1000).toFixed(1)}s` : '';const fullContent = content + timeSuffix;+ if (!fullContent.trim()) {+ logger.info({ targetId }, 'Telegram send: skipping empty message');+ return;+ }const html = mdToTelegram(fullContent);const chunks = this.splitMessage(html, MAX_MESSAGE_LENGTH);@@ -436,16 +440,25 @@ export class TelegramChannel extends BaseChannel {// final edit failed}}- } else {+ } else if (full.trim()) {const html = mdToTelegram(full);+ const stripped = this.stripHtml(html);try {await this.bot.api.sendMessage(chatId, html, { parse_mode: 'HTML' });} catch {- await this.bot.api.sendMessage(chatId, this.stripHtml(html));+ if (stripped.trim()) {+ try {+ await this.bot.api.sendMessage(chatId, stripped);+ } catch {+ // plain text send also failed+ }+ }}}return full;+ } catch {+ return '';} finally {this.stopTypingLoop();}diff --git a/src/core/agent.ts b/src/core/agent.tsindex 98c1c659..f73bfd2c 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -647,7 +647,7 @@ export class Agent {return;}- const finalText = streamedText || result.text;+ const finalText = (streamedText || result.text || '').trim() || '(no text response)';this.tokenBudget.recordUsage({provider: usedProvider!.name,@@ -687,7 +687,7 @@ export class Agent {if (channel && msg.channelType !== 'internal') {const elapsed = Date.now() - startTime;- if (streamedText) {+ if (streamedText && streamedText.trim()) {logger.info({ channelType: msg.channelType, elapsed }, 'Streamed response completed');} else {logger.info({ channelType: msg.channelType, targetId: msg.channelId }, 'Sending response');