Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix: cross-platform compatibility and better-sqlite3 optional dependency
Salman Qureshif392202ca467
diff --git a/package.json b/package.jsonindex 8cf2ba02..fe58ac6e 100644--- a/package.json+++ b/package.json@@ -15,7 +15,8 @@"typecheck": "tsc --noEmit","test": "vitest run","test:watch": "vitest",- "prepublishOnly": "npm run build"+ "prepublishOnly": "npm run build",+ "preinstall": "node scripts/check-native-deps.js"},"keywords": ["ai",@@ -58,7 +59,6 @@"@ai-sdk/openai": "^1.3.0","@grammyjs/auto-retry": "^2.0.2","ai": "^4.3.0",- "better-sqlite3": "^12.9.0","chalk": "^5.4.0","commander": "^12.1.0","dotenv": "^16.4.7",@@ -71,6 +71,9 @@"yaml": "^2.7.0","zod": "^3.25.76"},+ "optionalDependencies": {+ "better-sqlite3": "^12.9.0"+ },"devDependencies": {"@types/better-sqlite3": "^7.6.13","@types/node": "^22.13.0",@@ -81,6 +84,9 @@"vitest": "^3.0.0"},"engines": {- "node": ">=18.0.0"+ "node": ">=20.0.0"+ },+ "overrides": {+ "better-sqlite3": "^12.9.0"}}diff --git a/scripts/check-native-deps.js b/scripts/check-native-deps.jsnew file mode 100644index 00000000..108128c6--- /dev/null+++ b/scripts/check-native-deps.js@@ -0,0 +1,62 @@+#!/usr/bin/env node+const { execSync } = require('child_process');+const { platform } = require('os');++console.log('\u263F Checking native build prerequisites for better-sqlite3...\n');++let missing = false;+const isWin = platform() === 'win32';++if (!isWin) {+ if (!commandExists('make')) {+ console.log('\u26A0 \'make\' not found \u2014 better-sqlite3 may not compile.');+ console.log(' Install with: sudo apt-get install build-essential (Debian/Ubuntu)');+ console.log(' sudo yum groupinstall "Development Tools" (RHEL/CentOS)');+ missing = true;+ }+ if (!commandExists('gcc') && !commandExists('cc')) {+ console.log('\u26A0 C compiler not found \u2014 better-sqlite3 may not compile.');+ console.log(' Install with: sudo apt-get install gcc (Debian/Ubuntu)');+ missing = true;+ }+ if (!commandExists('python3') && !commandExists('python')) {+ console.log('\u26A0 Python not found \u2014 better-sqlite3 may not compile.');+ console.log(' Install with: sudo apt-get install python3 (Debian/Ubuntu)');+ missing = true;+ }+} else {+ if (!commandExists('cl') && !commandExists('gcc')) {+ console.log('\u26A0 C compiler not found \u2014 better-sqlite3 may not compile.');+ console.log(' Install Visual Studio Build Tools: npm install --global windows-build-tools');+ console.log(' Or install Visual Studio with C++ workload.');+ missing = true;+ }+}++const nodeVersion = process.version;+const nodeMajor = parseInt(nodeVersion.replace(/^v/, '').split('.')[0], 10);++if (nodeMajor < 20) {+ console.log(`\u26A0 Node.js ${nodeVersion} detected \u2014 better-sqlite3 v12 requires Node >= 20.`);+ console.log(' Upgrade with: nvm install 20');+ missing = true;+}++if (!missing) {+ console.log('\u2713 All native build prerequisites found.\n');+} else {+ console.log('');+ console.log(' Second brain memory will be disabled until the above are resolved.');+ console.log(' The rest of mercury-agent will work fine without better-sqlite3.\n');+}++function commandExists(cmd) {+ const isWin = platform() === 'win32';+ const checkCmd = isWin ? `where ${cmd}` : `command -v ${cmd}`;+ try {+ execSync(checkCmd, { stdio: 'pipe' });+ return true;+ } catch {+ return false;+ }+}\ No newline at end of filediff --git a/scripts/check-native-deps.sh b/scripts/check-native-deps.shnew file mode 100755index 00000000..b9a3448d--- /dev/null+++ b/scripts/check-native-deps.sh@@ -0,0 +1,45 @@+#!/usr/bin/env bash+# Checks for native build tool prerequisites needed by optional native modules (better-sqlite3).+# This is informational — it does NOT block the install, but warns the user early.+set -euo pipefail++echo "☿ Checking native build tool prerequisites..."++missing=0++if ! command -v make &>/dev/null; then+ echo "⚠ 'make' not found — better-sqlite3 will not compile."+ echo " Install with: sudo apt-get install build-essential (Debian/Ubuntu)"+ echo " sudo yum groupinstall 'Development Tools' (RHEL/CentOS)"+ missing=1+fi++if ! command -v gcc &>/dev/null && ! command -v cc &>/dev/null; then+ echo "⚠ C compiler not found — better-sqlite3 will not compile."+ echo " Install with: sudo apt-get install gcc (Debian/Ubuntu)"+ echo " sudo yum install gcc (RHEL/CentOS)"+ missing=1+fi++if ! command -v python3 &>/dev/null && ! command -v python &>/dev/null; then+ echo "⚠ Python not found — better-sqlite3 will not compile."+ echo " Install with: sudo apt-get install python3 (Debian/Ubuntu)"+ missing=1+fi++node_version=$(node -v 2>/dev/null || echo "unknown")+node_major=$(echo "$node_version" | sed 's/^v\([0-9]*\).*/\1/' 2>/dev/null || echo "0")++if [ "$node_major" -lt 20 ] 2>/dev/null; then+ echo "⚠ Node.js $node_version detected — better-sqlite3 v12 requires Node >= 20."+ echo " Upgrade with: nvm install 20"+ missing=1+fi++if [ "$missing" -eq 0 ]; then+ echo "✓ All native build prerequisites found."+else+ echo ""+ echo " Second brain memory will be disabled until the above are resolved."+ echo " The rest of mercury-agent will work fine without better-sqlite3."+fi\ No newline at end of filediff --git a/src/capabilities/filesystem/list-dir.ts b/src/capabilities/filesystem/list-dir.tsindex 148ba452..b22f90fd 100644--- a/src/capabilities/filesystem/list-dir.ts+++ b/src/capabilities/filesystem/list-dir.ts@@ -1,7 +1,7 @@import { tool } from 'ai';import { z } from 'zod';import { existsSync, readdirSync, statSync } from 'node:fs';-import { resolve, isAbsolute } from 'node:path';+import { resolve, isAbsolute, join } from 'node:path';import type { PermissionManager } from '../permissions.js';export function createListDirTool(permissions: PermissionManager, getCwd: () => string) {@@ -52,10 +52,6 @@ export function createListDirTool(permissions: PermissionManager, getCwd: () =>});}-function join(base: string, name: string): string {- return base.endsWith('/') ? base + name : base + '/' + name;-}-function formatSize(bytes: number): string {if (bytes < 1024) return `${bytes}B`;if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;diff --git a/src/capabilities/git/git-commit.ts b/src/capabilities/git/git-commit.tsindex b6470357..95defd47 100644--- a/src/capabilities/git/git-commit.ts+++ b/src/capabilities/git/git-commit.ts@@ -1,6 +1,8 @@import { tool } from 'ai';import { z } from 'zod';import { execSync } from 'node:child_process';+import { writeFileSync, unlinkSync } from 'node:fs';+import { join } from 'node:path';const CO_AUTHOR = 'Mercury <[email protected]>';@@ -13,13 +15,21 @@ export function createGitCommitTool(getCwd: () => string) {execute: async ({ message }) => {try {const fullMessage = `${message}\n\nCo-authored-by: ${CO_AUTHOR}`;- const escapedMsg = fullMessage.replace(/"/g, '\\"');- const result = execSync(`git commit -m "${escapedMsg}"`, { encoding: 'utf-8', timeout: 10000, cwd: getCwd() });+ const cwd = getCwd();+ const msgFilePath = join(cwd, '.git', 'MERCU_MSG');+ writeFileSync(msgFilePath, fullMessage, 'utf-8');+ const result = execSync(`git commit -F "${msgFilePath}"`, {+ encoding: 'utf-8',+ timeout: 10000,+ cwd,+ });+ try { unlinkSync(msgFilePath); } catch {}return result.trim() || 'Committed successfully.';} catch (err: any) {+ try { unlinkSync(join(getCwd(), '.git', 'MERCU_MSG')); } catch {}const stderr = err.stderr?.trim() || '';if (stderr.includes('nothing to commit')) {- return 'Nothing to commit — no staged changes.';+ return 'Nothing to commit \u2014 no staged changes.';}return `Error: ${stderr || err.message}`;}diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.tsindex 3a3f1966..adb88693 100644--- a/src/capabilities/permissions.ts+++ b/src/capabilities/permissions.ts@@ -66,6 +66,14 @@ const DEFAULT_MANIFEST: PermissionsManifest = {'kill -9 1','> /dev/sda','mv /* /dev/null',+ 'del /s /q C:\\*',+ 'rmdir /s /q C:\\*',+ 'format *',+ 'icacls * C:\\* /grant',+ 'net user *',+ 'netsh *',+ 'reg delete *',+ 'cmd /c rd /s /q *',],autoApproved: ['ls *',@@ -93,6 +101,14 @@ const DEFAULT_MANIFEST: PermissionsManifest = {'uname *','curl *','wget *',+ 'dir *',+ 'type *',+ 'cd *',+ 'where *',+ 'tree *',+ 'findstr *',+ 'tasklist *',+ 'systeminfo *',],needsApproval: ['npm publish *',@@ -110,6 +126,12 @@ const DEFAULT_MANIFEST: PermissionsManifest = {'chmod *','mkdir *','rmdir *',+ 'xcopy *',+ 'robocopy *',+ 'del *',+ 'rd /s *',+ 'powershell *',+ 'cmd /c *',],cwdOnly: true,},diff --git a/src/capabilities/shell/blocklist.ts b/src/capabilities/shell/blocklist.tsindex 41aa53f8..49a86fd4 100644--- a/src/capabilities/shell/blocklist.ts+++ b/src/capabilities/shell/blocklist.ts@@ -16,6 +16,14 @@ export const BLOCKED_COMMANDS = ['kill -9 1','> /dev/sda','mv /* /dev/null',+ 'del /s /q C:\\*',+ 'rmdir /s /q C:\\*',+ 'format *',+ 'icacls * C:\\* /grant',+ 'net user *',+ 'netsh *',+ 'reg delete *',+ 'cmd /c rd /s /q *',];export const AUTO_APPROVED_COMMANDS = [@@ -42,6 +50,14 @@ export const AUTO_APPROVED_COMMANDS = ['df *','du *','uname *',+ 'dir *',+ 'type *',+ 'cd *',+ 'where *',+ 'tree *',+ 'findstr *',+ 'tasklist *',+ 'systeminfo *',];export const NEEDS_APPROVAL_COMMANDS = [@@ -60,4 +76,10 @@ export const NEEDS_APPROVAL_COMMANDS = ['chmod *','mkdir *','rmdir *',+ 'xcopy *',+ 'robocopy *',+ 'del *',+ 'rd /s *',+ 'powershell *',+ 'cmd /c *',];\ No newline at end of filediff --git a/src/capabilities/shell/run-command.ts b/src/capabilities/shell/run-command.tsindex 171ba24e..09766b23 100644--- a/src/capabilities/shell/run-command.ts+++ b/src/capabilities/shell/run-command.ts@@ -3,6 +3,7 @@ import { z } from 'zod';import { execSync } from 'node:child_process';import { resolve, isAbsolute } from 'node:path';import { existsSync } from 'node:fs';+import { homedir } from 'node:os';import type { PermissionManager } from '../permissions.js';import { logger } from '../../utils/logger.js';@@ -65,7 +66,7 @@ function detectCd(command: string, currentCwd: string, setCwd: (dir: string) =>const cdOnly = trimmed.match(/^cd\s+(.+)$/);if (cdOnly) {- const target = cdOnly[1].replace(/^["']|["']$/g, '').replace(/~/, process.env.HOME || '');+ const target = cdOnly[1].replace(/^["']|["']$/g, '').replace(/^~/, homedir());const resolved = isAbsolute(target) ? target : resolve(currentCwd, target);if (existsSync(resolved)) {setCwd(resolved);@@ -75,7 +76,7 @@ function detectCd(command: string, currentCwd: string, setCwd: (dir: string) =>const cdChain = trimmed.match(/cd\s+(.+?)\s*&&/);if (cdChain) {- const target = cdChain[1].replace(/^["']|["']$/g, '').replace(/~/, process.env.HOME || '');+ const target = cdChain[1].replace(/^["']|["']$/g, '').replace(/^~/, homedir());const resolved = isAbsolute(target) ? target : resolve(currentCwd, target);if (existsSync(resolved)) {setCwd(resolved);diff --git a/src/cli/service.ts b/src/cli/service.tsindex 78a57916..969dd651 100644--- a/src/cli/service.ts+++ b/src/cli/service.ts@@ -33,7 +33,10 @@ function getNodeBinPath(): string {}function getDistPath(): string {- return join(process.argv[1] || '/usr/local/bin/mercury', '..', '..', 'lib', 'node_modules', '@cosmicstack', 'mercury-agent', 'dist', 'index.js');+ if (!process.argv[1]) {+ return join(homedir(), '.nvm', 'versions', 'node', `v${process.version.slice(1)}`, 'lib', 'node_modules', '@cosmicstack', 'mercury-agent', 'dist', 'index.js');+ }+ return join(process.argv[1], '..', '..', 'lib', 'node_modules', '@cosmicstack', 'mercury-agent', 'dist', 'index.js');}export function installService(): void {diff --git a/src/core/agent.ts b/src/core/agent.tsindex f73bfd2c..6e69584a 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -31,11 +31,13 @@ import {} from '../utils/config.js';class ToolCallLoopDetector {- private recentCalls: Array<{ tool: string; params: string }> = [];+ private recentCalls: Array<{ tool: string; params: string; failed: boolean }> = [];private totalCalls = 0;private hardAborted = false;+ private recentStepTexts: Array<string> = [];private static readonly ABSOLUTE_MAX = 25;+ private static readonly FAILED_ABSOLUTE_MAX = 12;private static readonly HIGH_TOLERANCE_TOOLS = new Set(['fetch_url',@@ -43,28 +45,48 @@ class ToolCallLoopDetector {'list_dir','web_search','github_api',- 'run_command',]);- private static getIdenticalThreshold(): number {- return 3;- }-- private static getSameToolThreshold(toolName: string): number {- return ToolCallLoopDetector.HIGH_TOLERANCE_TOOLS.has(toolName) ? 8 : 4;+ private static readonly IDENTICAL_THRESHOLD = 3;+ private static readonly SIMILAR_THRESHOLD = 4;+ private static readonly TEXT_REPEAT_THRESHOLD = 3;+ private static readonly MAX_STEP_TEXTS = 12;++ private static getSameToolThreshold(toolName: string, failingCount: number): number {+ const baseHigh = 5;+ const baseNormal = 3;+ const isHigh = ToolCallLoopDetector.HIGH_TOLERANCE_TOOLS.has(toolName);+ let threshold = isHigh ? baseHigh : baseNormal;+ if (failingCount >= 3) {+ threshold = Math.min(threshold, isHigh ? 3 : 2);+ }+ return threshold;}- record(toolName: string, params: Record<string, any>): void {+ record(toolName: string, params: Record<string, any>, failed: boolean = false): void {const paramsKey = JSON.stringify(params).slice(0, 200);- this.recentCalls.push({ tool: toolName, params: paramsKey });+ this.recentCalls.push({ tool: toolName, params: paramsKey, failed });this.totalCalls++;if (this.recentCalls.length > 30) {this.recentCalls.shift();}}+ recordStepText(text: string): void {+ if (!text || text.length < 10) return;+ const normalized = text.toLowerCase().replace(/\s+/g, ' ').trim().slice(0, 200);+ if (!normalized) return;+ this.recentStepTexts.push(normalized);+ if (this.recentStepTexts.length > ToolCallLoopDetector.MAX_STEP_TEXTS) {+ this.recentStepTexts.shift();+ }+ }+detectAbsoluteLimit(): boolean {- return this.totalCalls >= ToolCallLoopDetector.ABSOLUTE_MAX;+ if (this.totalCalls >= ToolCallLoopDetector.ABSOLUTE_MAX) return true;+ const failCount = this.recentCalls.filter(c => c.failed).length;+ if (failCount >= ToolCallLoopDetector.FAILED_ABSOLUTE_MAX) return true;+ return false;}detectIdentical(): { tool: string; count: number; message: string } | null {@@ -81,7 +103,7 @@ class ToolCallLoopDetector {}}- if (identicalCount >= ToolCallLoopDetector.getIdenticalThreshold()) {+ if (identicalCount >= ToolCallLoopDetector.IDENTICAL_THRESHOLD) {this.hardAborted = true;return {tool: last.tool,@@ -93,21 +115,88 @@ class ToolCallLoopDetector {return null;}+ detectSimilarLoop(): { tool: string; count: number; message: string } | null {+ if (this.recentCalls.length < 4) return null;++ const last = this.recentCalls[this.recentCalls.length - 1];+ let similarCount = 0;++ for (let i = this.recentCalls.length - 1; i >= 0; i--) {+ const call = this.recentCalls[i];+ if (call.tool !== last.tool) break;+ if (call.failed || last.failed) {+ similarCount++;+ } else {+ break;+ }+ }++ if (similarCount >= ToolCallLoopDetector.SIMILAR_THRESHOLD) {+ this.hardAborted = true;+ return {+ tool: last.tool,+ count: similarCount,+ message: `[SYSTEM] You called "${last.tool}" ${similarCount} times with different params but all are failing. This is a failing loop — stop immediately. Tell the user you cannot complete this task.`,+ };+ }++ return null;+ }++ detectTextRepetition(): { pattern: string; count: number } | null {+ if (this.recentStepTexts.length < ToolCallLoopDetector.TEXT_REPEAT_THRESHOLD) return null;++ const texts = this.recentStepTexts;+ const last = texts[texts.length - 1];++ let repeatCount = 0;+ for (let i = texts.length - 1; i >= 0; i--) {+ const similarity = this.textSimilarity(last, texts[i]);+ if (similarity >= 0.7) {+ repeatCount++;+ } else {+ break;+ }+ }++ if (repeatCount >= ToolCallLoopDetector.TEXT_REPEAT_THRESHOLD) {+ return {+ pattern: last.slice(0, 60),+ count: repeatCount,+ };+ }++ return null;+ }++ private textSimilarity(a: string, b: string): number {+ if (a === b) return 1;+ if (!a || !b) return 0;++ const setA = new Set(a.split(' '));+ const setB = new Set(b.split(' '));+ const intersection = [...setA].filter(w => setB.has(w)).length;+ const union = new Set([...setA, ...setB]).size;+ return union === 0 ? 0 : intersection / union;+ }+detectSameTool(): { tool: string; count: number } | null {if (this.recentCalls.length < 3) return null;const last = this.recentCalls[this.recentCalls.length - 1];let consecutiveCount = 0;+ let failingConsecutive = 0;for (let i = this.recentCalls.length - 1; i >= 0; i--) {if (this.recentCalls[i].tool === last.tool) {consecutiveCount++;+ if (this.recentCalls[i].failed) failingConsecutive++;} else {break;}}- const threshold = ToolCallLoopDetector.getSameToolThreshold(last.tool);+ const threshold = ToolCallLoopDetector.getSameToolThreshold(last.tool, failingConsecutive);if (consecutiveCount >= threshold) {return { tool: last.tool, count: consecutiveCount };}@@ -136,6 +225,7 @@ class ToolCallLoopDetector {this.recentCalls = [];this.totalCalls = 0;this.hardAborted = false;+ this.recentStepTexts = [];}}@@ -316,7 +406,7 @@ export class Agent {const messages: any[] = [];- const recentSteps = this.shortTerm.getRecent(msg.channelId, 4);+ const recentSteps = this.shortTerm.getRecent(msg.channelId, 6);let loopWarning: string | null = null;if (recentSteps.length >= 3) {const toolCallPattern = /\[Using: (.+?)\]/g;@@ -335,11 +425,26 @@ export class Agent {loopWarning = `[SYSTEM WARNING] You have called ${last3[0]} 3+ times in a row with the same result. Stop repeating this call. Try a different approach — if you're failing on permissions, try a different path. If you're failing on git push auth, use github_api with PUT /repos/{owner}/{repo}/contents/{path} to push files directly through the API.`;}}++ if (!loopWarning) {+ const assistantMessages = recentSteps.filter(m => m.role === 'assistant' && m.content.length > 20);+ if (assistantMessages.length >= 3) {+ const last3 = assistantMessages.slice(-3);+ const normalizeText = (t: string) => t.toLowerCase().replace(/[^\w\s]/g, '').replace(/\s+/g, ' ').trim().slice(0, 150);+ const normalized = last3.map(m => normalizeText(m.content));+ const words0 = new Set(normalized[0].split(' '));+ const overlap01 = normalized[0] && normalized[1] ? [...words0].filter(w => new Set(normalized[1].split(' ')).has(w)).length / Math.max(words0.size, 1) : 0;+ const overlap12 = normalized[1] && normalized[2] ? [...new Set(normalized[1].split(' '))].filter(w => new Set(normalized[2].split(' ')).has(w)).length / Math.max(new Set(normalized[1].split(' ')).size, 1) : 0;+ if (overlap01 > 0.75 && overlap12 > 0.75) {+ loopWarning = `[SYSTEM WARNING] Your last 3 responses are nearly identical. You are stuck in a text repetition loop. Stop immediately and give a completely different response. If you cannot complete the task, tell the user clearly why.`;+ }+ }+ }}if (loopWarning) {messages.push({ role: 'user', content: loopWarning });- messages.push({ role: 'assistant', content: 'Understood. I will try a different approach.' });+ messages.push({ role: 'assistant', content: 'Acknowledged. I will stop repeating and respond differently, or clearly state if the task cannot be completed.' });}if (this.userMemory) {@@ -412,11 +517,21 @@ export class Agent {maxSteps: MAX_STEPS,abortSignal: loopAbortController.signal,onStepFinish: async ({ toolCalls, toolResults }) => {- if (toolCalls && toolCalls.length > 0) {+ if (toolCalls && toolResults && toolCalls.length > 0) {const names = toolCalls.map((tc: any) => tc.toolName).join(', ');logger.info({ tools: names }, 'Tool call step');- for (const tc of toolCalls) {- loopDetector.record(tc.toolName, tc.args as Record<string, any>);+ for (let i = 0; i < toolCalls.length; i++) {+ const tc = toolCalls[i];+ const tr = toolResults[i] as any;+ const resultStr = typeof tr?.result === 'string' ? tr.result : JSON.stringify(tr?.result ?? '');+ const failed = resultStr.length < 5000 && (+ resultStr.startsWith('Error:') ||+ resultStr.startsWith('⚠') ||+ resultStr.includes('exited with code') ||+ resultStr.includes('Command failed') ||+ resultStr.startsWith('Command exited with code')+ );+ loopDetector.record(tc.toolName, tc.args as Record<string, any>, failed);}if (loopDetector.detectAbsoluteLimit()) {logger.warn('Absolute tool call limit reached — aborting');@@ -439,6 +554,16 @@ export class Agent {loopAbortController.abort();return;}+ const similarLoop = loopDetector.detectSimilarLoop();+ if (similarLoop) {+ logger.warn({ tool: similarLoop.tool, count: similarLoop.count }, 'Failing loop detected — aborting');+ if (!loopWarningSent && channel && msg.channelType !== 'internal') {+ loopWarningSent = true;+ await channel.send(`⚠ Failing loop detected — ${similarLoop.tool} called ${similarLoop.count}x, all failing. Stopping.`, msg.channelId).catch(() => {});+ }+ loopAbortController.abort();+ return;+ }const softLoop = loopDetector.detectSameTool();if (softLoop && !loopWarningSent && channel && msg.channelType !== 'internal') {if (this.capabilities.permissions.isAutoApproveAll()) {@@ -490,6 +615,20 @@ export class Agent {await channel.send(` [Using: ${names}]`, msg.channelId).catch(() => {});}}+ } else if (toolResults === undefined || (toolCalls === undefined)) {+ const stepText = (toolResults as any)?.text ?? '';+ if (stepText) {+ loopDetector.recordStepText(String(stepText));+ }+ const textRepeat = loopDetector.detectTextRepetition();+ if (textRepeat) {+ logger.warn({ pattern: textRepeat.pattern, count: textRepeat.count }, 'Text repetition loop detected — aborting');+ if (!loopWarningSent && channel && msg.channelType !== 'internal') {+ loopWarningSent = true;+ await channel.send('⚠ I keep generating the same response. Stopping to prevent repetition.', msg.channelId).catch(() => {});+ }+ loopAbortController.abort();+ }}},});@@ -520,6 +659,7 @@ export class Agent {result = { text: fullText, usage };streamedText = fullText;+ loopDetector.recordStepText(fullText);} else {result = await generateText({model: provider.getModelInstance(),@@ -529,11 +669,21 @@ export class Agent {maxSteps: MAX_STEPS,abortSignal: loopAbortController.signal,onStepFinish: async ({ toolCalls, toolResults }) => {- if (toolCalls && toolCalls.length > 0) {+ if (toolCalls && toolResults && toolCalls.length > 0) {const names = toolCalls.map((tc: any) => tc.toolName).join(', ');logger.info({ tools: names }, 'Tool call step');- for (const tc of toolCalls) {- loopDetector.record(tc.toolName, tc.args as Record<string, any>);+ for (let i = 0; i < toolCalls.length; i++) {+ const tc = toolCalls[i];+ const tr = toolResults[i] as any;+ const resultStr = typeof tr?.result === 'string' ? tr.result : JSON.stringify(tr?.result ?? '');+ const failed = resultStr.length < 5000 && (+ resultStr.startsWith('Error:') ||+ resultStr.startsWith('⚠') ||+ resultStr.includes('exited with code') ||+ resultStr.includes('Command failed') ||+ resultStr.startsWith('Command exited with code')+ );+ loopDetector.record(tc.toolName, tc.args as Record<string, any>, failed);}if (loopDetector.detectAbsoluteLimit()) {logger.warn('Absolute tool call limit reached — aborting');@@ -556,6 +706,16 @@ export class Agent {loopAbortController.abort();return;}+ const similarLoop = loopDetector.detectSimilarLoop();+ if (similarLoop) {+ logger.warn({ tool: similarLoop.tool, count: similarLoop.count }, 'Failing loop detected — aborting');+ if (!loopWarningSent && channel && msg.channelType !== 'internal') {+ loopWarningSent = true;+ await channel.send(`⚠ Failing loop detected — ${similarLoop.tool} called ${similarLoop.count}x, all failing. Stopping.`, msg.channelId).catch(() => {});+ }+ loopAbortController.abort();+ return;+ }const softLoop = loopDetector.detectSameTool();if (softLoop && !loopWarningSent && channel && msg.channelType !== 'internal') {if (this.capabilities.permissions.isAutoApproveAll()) {@@ -607,6 +767,20 @@ export class Agent {await channel.send(` [Using: ${names}]`, msg.channelId).catch(() => {});}}+ } else if (toolResults === undefined || (toolCalls === undefined)) {+ const stepText = (toolResults as any)?.text ?? '';+ if (stepText) {+ loopDetector.recordStepText(String(stepText));+ }+ const textRepeat = loopDetector.detectTextRepetition();+ if (textRepeat) {+ logger.warn({ pattern: textRepeat.pattern, count: textRepeat.count }, 'Text repetition loop detected — aborting');+ if (!loopWarningSent && channel && msg.channelType !== 'internal') {+ loopWarningSent = true;+ await channel.send('⚠ I keep generating the same response. Stopping to prevent repetition.', msg.channelId).catch(() => {});+ }+ loopAbortController.abort();+ }}},});@@ -622,7 +796,7 @@ export class Agent {result = { text: streamedText, usage: undefined };}if (!result) {- result = { text: 'I stopped because I was repeating the same tool calls. What would you like me to do differently?', usage: undefined };+ result = { text: 'I stopped because I detected I was stuck in a loop (repeating the same action without progress). I cannot complete this task as requested. Please let me know if you\'d like me to try a completely different approach, or if there\'s something else I can help with.', usage: undefined };}if (usedProvider) {this.providers.markSuccess(usedProvider.name);diff --git a/src/index.ts b/src/index.tsindex 05bae3fc..341d4be5 100644--- a/src/index.ts+++ b/src/index.ts@@ -30,6 +30,7 @@ import { logger } from './utils/logger.js';import { Identity } from './soul/identity.js';import { ShortTermMemory, LongTermMemory, EpisodicMemory, migrateLegacyMemory } from './memory/store.js';import { UserMemoryStore } from './memory/user-memory.js';+import { isBetterSqlite3Available } from './memory/second-brain-db.js';import { ProviderRegistry } from './providers/registry.js';import { Agent } from './core/agent.js';import { Scheduler } from './core/scheduler.js';@@ -873,7 +874,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {const episodic = new EpisodicMemory(config);let userMemory: UserMemoryStore | null = null;- if (config.memory.secondBrain?.enabled !== false) {+ if (config.memory.secondBrain?.enabled !== false && isBetterSqlite3Available()) {try {userMemory = new UserMemoryStore(config);if (!isDaemon) {@@ -885,6 +886,11 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {logger.warn({ err }, 'Second brain initialization failed, continuing without it');userMemory = null;}+ } else if (config.memory.secondBrain?.enabled !== false && !isBetterSqlite3Available()) {+ logger.warn(+ 'better-sqlite3 is not available — second brain memory is disabled. ' ++ 'To enable it, install build tools (make, gcc/g++, python3) and ensure Node >= 20, then reinstall.'+ );}const channels = new ChannelRegistry(config);diff --git a/src/memory/index.ts b/src/memory/index.tsindex 17a15cc7..9f110aa5 100644--- a/src/memory/index.ts+++ b/src/memory/index.ts@@ -2,5 +2,5 @@ export { ShortTermMemory, LongTermMemory, EpisodicMemory } from './store.js';export type { MemoryEntry, LongTermFact, EpisodicEvent } from './store.js';export { UserMemoryStore } from './user-memory.js';export type { UserMemoryType, UserMemoryRecord, UserMemoryCandidate, UserMemorySummary, RetrievedUserMemory } from './user-memory.js';-export { SecondBrainDB } from './second-brain-db.js';+export { SecondBrainDB, isBetterSqlite3Available } from './second-brain-db.js';export type { MemoryRow } from './second-brain-db.js';\ No newline at end of filediff --git a/src/memory/second-brain-db.ts b/src/memory/second-brain-db.tsindex 15239a14..663d0cf6 100644--- a/src/memory/second-brain-db.ts+++ b/src/memory/second-brain-db.ts@@ -1,8 +1,37 @@-import Database from 'better-sqlite3';-import { existsSync, mkdirSync } from 'node:fs';-import { dirname } from 'node:path';+import { existsSync, mkdirSync, rmSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { tmpdir } from 'node:os';+import { createRequire } from 'node:module';import { logger } from '../utils/logger.js';+type BetterSqlite3Database = import('better-sqlite3').Database;++const require = createRequire(import.meta.url);++let syncDatabaseClass: typeof import('better-sqlite3') | null = null;+let availabilityChecked = false;+let available = false;++try {+ const mod = require('better-sqlite3');+ const probeDir = join(tmpdir(), `mercury-sqlite3-probe-${process.pid}`);+ try {+ mkdirSync(probeDir, { recursive: true });+ const probeDb = new mod(join(probeDir, 'probe.db'));+ probeDb.close();+ rmSync(probeDir, { recursive: true, force: true });+ syncDatabaseClass = mod;+ } catch {+ syncDatabaseClass = null;+ }+} catch {+ syncDatabaseClass = null;+}++export function isBetterSqlite3Available(): boolean {+ return syncDatabaseClass !== null;+}+export interface MemoryRow {id: string;user_key: string;@@ -27,14 +56,21 @@ export interface MemoryRow {}export class SecondBrainDB {- private db: Database.Database;+ private db: BetterSqlite3Database;constructor(dbPath: string) {+ if (!syncDatabaseClass) {+ throw new Error(+ 'better-sqlite3 is not available — second brain memory requires it. ' ++ 'Install build tools (make, gcc/g++, python3) or upgrade to Node >= 20. ' ++ 'See: https://github.com/WiseLibs/better-sqlite3/blob/master/docs/compilation.md'+ );+ }const dir = dirname(dbPath);if (!existsSync(dir)) {mkdirSync(dir, { recursive: true });}- this.db = new Database(dbPath);+ this.db = new syncDatabaseClass(dbPath);this.db.pragma('journal_mode = WAL');this.db.pragma('synchronous = NORMAL');}diff --git a/src/memory/store.ts b/src/memory/store.tsindex 3a534093..dd351892 100644--- a/src/memory/store.ts+++ b/src/memory/store.ts@@ -143,7 +143,7 @@ export class LongTermMemory {private load(): void {if (!existsSync(this.filepath)) return;const lines = readFileSync(this.filepath, 'utf-8')- .split('\n')+ .split(/\r?\n/).filter(Boolean);this.facts = lines.map(line => {@@ -191,7 +191,7 @@ export class EpisodicMemory {private load(): void {if (!existsSync(this.filepath)) return;const lines = readFileSync(this.filepath, 'utf-8')- .split('\n')+ .split(/\r?\n/).filter(Boolean);this.events = lines.map(line => {diff --git a/src/memory/user-memory.test.ts b/src/memory/user-memory.test.tsindex 36f7cffb..331c499a 100644--- a/src/memory/user-memory.test.ts+++ b/src/memory/user-memory.test.ts@@ -4,9 +4,12 @@ import { join } from 'node:path';import { afterEach, describe, expect, it } from 'vitest';import { getDefaultConfig } from '../utils/config.js';import { UserMemoryStore } from './user-memory.js';+import { isBetterSqlite3Available } from './second-brain-db.js';const tempDirs: string[] = [];+const sqliteAvailable = isBetterSqlite3Available();+function createStore(): UserMemoryStore {const dir = mkdtempSync(join(tmpdir(), 'mercury-sb-'));tempDirs.push(dir);@@ -27,7 +30,7 @@ afterEach(() => {});describe('UserMemoryStore', () => {- it('merges similar durable memories instead of duplicating them', () => {+ it.skipIf(!sqliteAvailable)('merges similar durable memories instead of duplicating them', () => {const store = createStore();store.remember([@@ -44,7 +47,7 @@ describe('UserMemoryStore', () => {expect(recent[0].summary).toContain('concise');});- it('retrieves only relevant records for a query', () => {+ it.skipIf(!sqliteAvailable)('retrieves only relevant records for a query', () => {const store = createStore();store.remember([@@ -62,7 +65,7 @@ describe('UserMemoryStore', () => {expect(result.context).toContain('Mercury');});- it('auto-resolves conflicts by dismissing the lower-confidence memory', () => {+ it.skipIf(!sqliteAvailable)('auto-resolves conflicts by dismissing the lower-confidence memory', () => {const store = createStore();store.remember([@@ -80,7 +83,7 @@ describe('UserMemoryStore', () => {expect(active[0].summary).not.toContain('does not');});- it('auto-resolves conflicts when incoming has higher confidence', () => {+ it.skipIf(!sqliteAvailable)('auto-resolves conflicts when incoming has higher confidence', () => {const store = createStore();store.remember([@@ -97,7 +100,7 @@ describe('UserMemoryStore', () => {expect(active[0].summary).toContain('does not prefer verbose');});- it('synthesizes a compact profile and reflection records from repeated signal', () => {+ it.skipIf(!sqliteAvailable)('synthesizes a compact profile and reflection records from repeated signal', () => {const store = createStore();store.remember([@@ -124,7 +127,7 @@ describe('UserMemoryStore', () => {expect(reflections.length).toBeGreaterThan(0);});- it('separates active state from durable profile', () => {+ it.skipIf(!sqliteAvailable)('separates active state from durable profile', () => {const store = createStore();store.remember([@@ -148,7 +151,7 @@ describe('UserMemoryStore', () => {expect(summary.profileSummary).toContain('second brain');});- it('supports pause and resume of learning', () => {+ it.skipIf(!sqliteAvailable)('supports pause and resume of learning', () => {const store = createStore();expect(store.isLearningPaused()).toBe(false);@@ -168,7 +171,7 @@ describe('UserMemoryStore', () => {expect(store.getSummary().total).toBe(1);});- it('clears all memories', () => {+ it.skipIf(!sqliteAvailable)('clears all memories', () => {const store = createStore();store.remember([@@ -185,7 +188,7 @@ describe('UserMemoryStore', () => {expect(store.getSummary().total).toBe(0);});- it('full-text search finds relevant memories', () => {+ it.skipIf(!sqliteAvailable)('full-text search finds relevant memories', () => {const store = createStore();store.remember([@@ -200,7 +203,7 @@ describe('UserMemoryStore', () => {expect(results[0].summary).toContain('knowledge management');});- it('deprioritizes stale inferred memories in retrieval', () => {+ it.skipIf(!sqliteAvailable)('deprioritizes stale inferred memories in retrieval', () => {const store = createStore();const [inferred] = store.remember([@@ -215,7 +218,7 @@ describe('UserMemoryStore', () => {expect(summary.profileSummary).toContain('second brain');});- it('stores weak memories that pass minimum threshold', () => {+ it.skipIf(!sqliteAvailable)('stores weak memories that pass minimum threshold', () => {const store = createStore();store.remember([@@ -225,7 +228,7 @@ describe('UserMemoryStore', () => {expect(store.getSummary().total).toBe(1);});- it('rejects memories below minimum confidence', () => {+ it.skipIf(!sqliteAvailable)('rejects memories below minimum confidence', () => {const store = createStore();store.remember([@@ -234,4 +237,8 @@ describe('UserMemoryStore', () => {expect(store.getSummary().total).toBe(0);});++ it('reports better-sqlite3 availability status', () => {+ expect(typeof sqliteAvailable).toBe('boolean');+ });});\ No newline at end of filediff --git a/tsup.config.ts b/tsup.config.tsindex ea2c5d7e..4bc56419 100644--- a/tsup.config.ts+++ b/tsup.config.ts@@ -14,5 +14,6 @@ export default defineConfig({"react","ink","grammy",+ "better-sqlite3",],});\ No newline at end of file