Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat: add Git, web, and file editing capabilities, and implement provider fallback and persistent token tracking

Salman Qureshi18df09363582
diff --git a/src/capabilities/filesystem/edit-file.ts b/src/capabilities/filesystem/edit-file.ts
new file mode 100644
index 00000000..1116e187
--- /dev/null
+++ b/src/capabilities/filesystem/edit-file.ts
@@ -0,0 +1,48 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { readFileSync, writeFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import type { PermissionManager } from '../permissions.js';
+
+export function createEditFileTool(permissions: PermissionManager) {
+ return tool({
+ description: 'Edit a file by replacing an exact string match with new content. Use this instead of write_file when you only need to change part of a file. The old_string must match exactly (including whitespace and indentation). Fails if old_string is not found or found multiple times.',
+ parameters: z.object({
+ path: z.string().describe('Absolute or relative path to the file'),
+ old_string: z.string().describe('The exact text to find in the file (must match exactly)'),
+ new_string: z.string().describe('The text to replace it with'),
+ }),
+ execute: async ({ path, old_string, new_string }) => {
+ const resolved = resolve(path);
+
+ const fsCheck = await permissions.checkFsAccess(resolved, 'write');
+ if (!fsCheck.allowed) {
+ return `Error: ${fsCheck.reason}`;
+ }
+
+ try {
+ const content = readFileSync(resolved, 'utf-8');
+
+ const count = content.split(old_string).length - 1;
+ if (count === 0) {
+ return `Error: old_string not found in ${path}. Make sure the text matches exactly, including whitespace and indentation.`;
+ }
+ if (count > 1) {
+ return `Error: old_string found ${count} times in ${path}. Provide more surrounding context to make the match unique.`;
+ }
+
+ const newContent = content.replace(old_string, new_string);
+ writeFileSync(resolved, newContent, 'utf-8');
+
+ const linesAdded = new_string.split('\n').length;
+ const linesRemoved = old_string.split('\n').length;
+ return `Edited ${path}: replaced ${linesRemoved} line(s) with ${linesAdded} line(s)`;
+ } catch (err: any) {
+ if (err.code === 'ENOENT') {
+ return `Error: File not found: ${path}. Use create_file to create new files.`;
+ }
+ return `Error editing file: ${err.message}`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/git/git-add.ts b/src/capabilities/git/git-add.ts
new file mode 100644
index 00000000..e514eb57
--- /dev/null
+++ b/src/capabilities/git/git-add.ts
@@ -0,0 +1,21 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { execSync } from 'node:child_process';
+
+export function createGitAddTool() {
+ return tool({
+ description: 'Add file contents to the index (staging area). Prepares files for commit.',
+ parameters: z.object({
+ paths: z.array(z.string()).describe('File paths to stage'),
+ }),
+ execute: async ({ paths }) => {
+ try {
+ const fileArgs = paths.map(p => `"${p}"`).join(' ');
+ const result = execSync(`git add ${fileArgs}`, { encoding: 'utf-8', timeout: 10000 });
+ return `Staged ${paths.length} file(s): ${paths.join(', ')}`;
+ } catch (err: any) {
+ return `Error: ${err.stderr?.trim() || err.message}`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/git/git-commit.ts b/src/capabilities/git/git-commit.ts
new file mode 100644
index 00000000..a4cc5bff
--- /dev/null
+++ b/src/capabilities/git/git-commit.ts
@@ -0,0 +1,25 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { execSync } from 'node:child_process';
+
+export function createGitCommitTool() {
+ return tool({
+ description: 'Record changes to the repository. Creates a new commit with staged changes.',
+ parameters: z.object({
+ message: z.string().describe('Commit message'),
+ }),
+ execute: async ({ message }) => {
+ try {
+ const escapedMsg = message.replace(/"/g, '\\"');
+ const result = execSync(`git commit -m "${escapedMsg}"`, { encoding: 'utf-8', timeout: 10000 });
+ return result.trim() || 'Committed successfully.';
+ } catch (err: any) {
+ const stderr = err.stderr?.trim() || '';
+ if (stderr.includes('nothing to commit')) {
+ return 'Nothing to commit — no staged changes.';
+ }
+ return `Error: ${stderr || err.message}`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/git/git-diff.ts b/src/capabilities/git/git-diff.ts
new file mode 100644
index 00000000..c5de70a0
--- /dev/null
+++ b/src/capabilities/git/git-diff.ts
@@ -0,0 +1,26 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { execSync } from 'node:child_process';
+
+export function createGitDiffTool() {
+ return tool({
+ description: 'Show changes between commits, commit and working tree, etc. Shows what has been modified.',
+ parameters: z.object({
+ path: z.string().optional().describe('File or directory to diff'),
+ staged: z.boolean().optional().describe('Show staged changes (cached) instead of unstaged'),
+ }),
+ execute: async ({ path, staged }) => {
+ try {
+ let cmd = 'git diff';
+ if (staged) cmd += ' --cached';
+ if (path) cmd += ` -- "${path}"`;
+ const result = execSync(cmd, { encoding: 'utf-8', timeout: 15000 });
+ if (!result.trim()) return 'No differences found.';
+ const truncated = result.length > 15000 ? result.slice(0, 15000) + '\n... (truncated)' : result;
+ return truncated;
+ } catch (err: any) {
+ return `Error: ${err.stderr?.trim() || err.message}`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/git/git-log.ts b/src/capabilities/git/git-log.ts
new file mode 100644
index 00000000..759fc65e
--- /dev/null
+++ b/src/capabilities/git/git-log.ts
@@ -0,0 +1,25 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { execSync } from 'node:child_process';
+
+export function createGitLogTool() {
+ return tool({
+ description: 'Show commit logs. Returns recent commit history with hash, author, date, and message.',
+ parameters: z.object({
+ count: z.number().optional().describe('Number of commits to show (default 10)'),
+ path: z.string().optional().describe('File or directory to show log for'),
+ }),
+ execute: async ({ count, path }) => {
+ try {
+ const n = count ?? 10;
+ let cmd = `git log --oneline --decorate -${n}`;
+ if (path) cmd += ` -- "${path}"`;
+ const result = execSync(cmd, { encoding: 'utf-8', timeout: 10000 });
+ if (!result.trim()) return 'No commits found.';
+ return result.trim();
+ } catch (err: any) {
+ return `Error: ${err.stderr?.trim() || err.message}`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/git/git-push.ts b/src/capabilities/git/git-push.ts
new file mode 100644
index 00000000..af48e8e1
--- /dev/null
+++ b/src/capabilities/git/git-push.ts
@@ -0,0 +1,33 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { execSync } from 'node:child_process';
+import type { PermissionManager } from '../permissions.js';
+
+export function createGitPushTool(permissions: PermissionManager) {
+ return tool({
+ description: 'Push commits to a remote repository. This modifies a remote and requires approval.',
+ parameters: z.object({
+ remote: z.string().optional().describe('Remote name (default: origin)'),
+ branch: z.string().optional().describe('Branch name (default: current branch)'),
+ }),
+ execute: async ({ remote, branch }) => {
+ const cmd = `git push ${remote || 'origin'} ${branch || ''}`.trim();
+ const check = await permissions.checkShellCommand(cmd);
+ if (!check.allowed && check.needsApproval) {
+ const baseCmd = 'git';
+ permissions.addPendingApproval(baseCmd);
+ return `⚠ This command pushes to a remote: ${cmd}\nAsk the user for permission. If they approve, try again. If they say "always", use the approve_command tool.`;
+ }
+ if (!check.allowed) {
+ return `Error: ${check.reason}`;
+ }
+
+ try {
+ const result = execSync(cmd, { encoding: 'utf-8', timeout: 30000 });
+ return result.trim() || 'Pushed successfully.';
+ } catch (err: any) {
+ return `Error: ${err.stderr?.trim() || err.message}`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/git/git-status.ts b/src/capabilities/git/git-status.ts
new file mode 100644
index 00000000..07f20f5e
--- /dev/null
+++ b/src/capabilities/git/git-status.ts
@@ -0,0 +1,22 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { execSync } from 'node:child_process';
+
+export function createGitStatusTool() {
+ return tool({
+ description: 'Show the working tree status. Returns staged, unstaged, and untracked files.',
+ parameters: z.object({
+ path: z.string().optional().describe('Path to check (defaults to current directory)'),
+ }),
+ execute: async ({ path }) => {
+ try {
+ const cmd = path ? `git -C "${path}" status --porcelain` : 'git status --porcelain';
+ const result = execSync(cmd, { encoding: 'utf-8', timeout: 10000 });
+ if (!result.trim()) return 'Working tree clean — no changes.';
+ return result.trim();
+ } catch (err: any) {
+ return `Error: ${err.stderr?.trim() || err.message}`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.ts
index f4b9d3de..90e7a7e8 100644
--- a/src/capabilities/registry.ts
+++ b/src/capabilities/registry.ts
@@ -5,6 +5,7 @@ import { createWriteFileTool } from './filesystem/write-file.js';
import { createCreateFileTool } from './filesystem/create-file.js';
import { createListDirTool } from './filesystem/list-dir.js';
import { createDeleteFileTool } from './filesystem/delete-file.js';
+import { createEditFileTool } from './filesystem/edit-file.js';
import { createRunCommandTool } from './shell/run-command.js';
import { createApproveCommandTool } from './shell/approve-command.js';
import { createInstallSkillTool } from './skills/install-skill.js';
@@ -13,8 +14,17 @@ import { createUseSkillTool } from './skills/use-skill.js';
import { createScheduleTaskTool } from './scheduler/schedule-task.js';
import { createListTasksTool } from './scheduler/list-tasks.js';
import { createCancelTaskTool } from './scheduler/cancel-task.js';
+import { createBudgetStatusTool } from './system/budget-status.js';
+import { createGitStatusTool } from './git/git-status.js';
+import { createGitDiffTool } from './git/git-diff.js';
+import { createGitLogTool } from './git/git-log.js';
+import { createGitAddTool } from './git/git-add.js';
+import { createGitCommitTool } from './git/git-commit.js';
+import { createGitPushTool } from './git/git-push.js';
+import { createFetchUrlTool } from './web/fetch-url.js';
import type { SkillLoader } from '../skills/loader.js';
import type { Scheduler } from '../core/scheduler.js';
+import type { TokenBudget } from '../utils/tokens.js';
import { logger } from '../utils/logger.js';
export class CapabilityRegistry {
@@ -22,11 +32,13 @@ export class CapabilityRegistry {
private tools: Record<string, Tool> = {};
private skillLoader?: SkillLoader;
private scheduler?: Scheduler;
+ private tokenBudget?: TokenBudget;
- constructor(skillLoader?: SkillLoader, scheduler?: Scheduler) {
+ constructor(skillLoader?: SkillLoader, scheduler?: Scheduler, tokenBudget?: TokenBudget) {
this.permissions = new PermissionManager();
this.skillLoader = skillLoader;
this.scheduler = scheduler;
+ this.tokenBudget = tokenBudget;
this.registerAll();
}
@@ -39,6 +51,7 @@ export class CapabilityRegistry {
this.tools.create_file = createCreateFileTool(this.permissions);
this.tools.list_dir = createListDirTool(this.permissions);
this.tools.delete_file = createDeleteFileTool(this.permissions);
+ this.tools.edit_file = createEditFileTool(this.permissions);
logger.info('Filesystem tools registered');
}
@@ -61,6 +74,24 @@ export class CapabilityRegistry {
this.tools.cancel_scheduled_task = createCancelTaskTool(this.scheduler);
logger.info('Scheduler tools registered');
}
+
+ if (this.tokenBudget) {
+ this.tools.budget_status = createBudgetStatusTool(this.tokenBudget);
+ logger.info('Budget tool registered');
+ }
+
+ if (manifest.capabilities.git?.enabled) {
+ this.tools.git_status = createGitStatusTool();
+ this.tools.git_diff = createGitDiffTool();
+ this.tools.git_log = createGitLogTool();
+ this.tools.git_add = createGitAddTool();
+ this.tools.git_commit = createGitCommitTool();
+ this.tools.git_push = createGitPushTool(this.permissions);
+ logger.info('Git tools registered');
+ }
+
+ this.tools.fetch_url = createFetchUrlTool();
+ logger.info('Web fetch tool registered');
}
getTools(): Record<string, Tool> {
diff --git a/src/capabilities/system/budget-status.ts b/src/capabilities/system/budget-status.ts
new file mode 100644
index 00000000..6031cab5
--- /dev/null
+++ b/src/capabilities/system/budget-status.ts
@@ -0,0 +1,13 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import type { TokenBudget } from '../../utils/tokens.js';
+
+export function createBudgetStatusTool(tokenBudget: TokenBudget) {
+ return tool({
+ description: 'Check the current token budget status — how many tokens have been used today, how many remain, and what percentage is consumed.',
+ parameters: z.object({}),
+ execute: async () => {
+ return tokenBudget.getStatusText();
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/web/fetch-url.ts b/src/capabilities/web/fetch-url.ts
new file mode 100644
index 00000000..1c3ee426
--- /dev/null
+++ b/src/capabilities/web/fetch-url.ts
@@ -0,0 +1,105 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+
+const MAX_CONTENT_LENGTH = 15000;
+
+function stripHtml(html: string): string {
+ let text = html;
+
+ text = text.replace(/<script[\s\S]*?<\/script>/gi, '');
+ text = text.replace(/<style[\s\S]*?<\/style>/gi, '');
+ text = text.replace(/<nav[\s\S]*?<\/nav>/gi, '');
+ text = text.replace(/<footer[\s\S]*?<\/footer>/gi, '');
+ text = text.replace(/<header[\s\S]*?<\/header>/gi, '');
+
+ text = text.replace(/<br\s*\/?>/gi, '\n');
+ text = text.replace(/<\/p>/gi, '\n');
+ text = text.replace(/<\/h[1-6]>/gi, '\n');
+ text = text.replace(/<\/li>/gi, '\n');
+ text = text.replace(/<\/div>/gi, '\n');
+ text = text.replace(/<hr\s*\/?>/gi, '\n---\n');
+
+ text = text.replace(/<a[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi, '[$2]($1)');
+ text = text.replace(/<img[^>]*alt="([^"]*)"[^>]*>/gi, '[image: $1]');
+ text = text.replace(/<code[^>]*>([\s\S]*?)<\/code>/gi, '`$1`');
+ text = text.replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gi, '\n```\n$1\n```\n');
+ text = text.replace(/<strong[^>]*>([\s\S]*?)<\/strong>/gi, '**$1**');
+ text = text.replace(/<em[^>]*>([\s\S]*?)<\/em>/gi, '*$1*');
+
+ text = text.replace(/<[^>]+>/g, '');
+
+ text = text.replace(/&amp;/g, '&');
+ text = text.replace(/&lt;/g, '<');
+ text = text.replace(/&gt;/g, '>');
+ text = text.replace(/&quot;/g, '"');
+ text = text.replace(/&#39;/g, "'");
+ text = text.replace(/&nbsp;/g, ' ');
+
+ text = text.replace(/\n{3,}/g, '\n\n');
+ text = text.trim();
+
+ return text;
+}
+
+export function createFetchUrlTool() {
+ return tool({
+ description: 'Fetch a URL and return its content as text. Strips HTML to readable markdown-like format. Useful for reading documentation, APIs, or web pages.',
+ parameters: z.object({
+ url: z.string().describe('The URL to fetch'),
+ format: z.enum(['text', 'markdown']).optional().describe('Output format (default: markdown)'),
+ }),
+ execute: async ({ url, format }) => {
+ const outputFormat = format ?? 'markdown';
+
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 15000);
+
+ const resp = await fetch(url, {
+ signal: controller.signal,
+ headers: {
+ 'User-Agent': 'Mercury-Agent/0.1.0',
+ 'Accept': 'text/html,application/json,text/plain',
+ },
+ });
+
+ clearTimeout(timeout);
+
+ if (!resp.ok) {
+ return `HTTP ${resp.status} ${resp.statusText} for ${url}`;
+ }
+
+ const contentType = resp.headers.get('content-type') || '';
+ const body = await resp.text();
+
+ if (contentType.includes('application/json')) {
+ try {
+ const json = JSON.parse(body);
+ const formatted = JSON.stringify(json, null, 2);
+ return formatted.length > MAX_CONTENT_LENGTH
+ ? formatted.slice(0, MAX_CONTENT_LENGTH) + '\n... (truncated)'
+ : formatted;
+ } catch {
+ return body.slice(0, MAX_CONTENT_LENGTH);
+ }
+ }
+
+ if (contentType.includes('text/html') && outputFormat === 'markdown') {
+ const text = stripHtml(body);
+ return text.length > MAX_CONTENT_LENGTH
+ ? text.slice(0, MAX_CONTENT_LENGTH) + '\n... (truncated)'
+ : text;
+ }
+
+ return body.length > MAX_CONTENT_LENGTH
+ ? body.slice(0, MAX_CONTENT_LENGTH) + '\n... (truncated)'
+ : body;
+ } catch (err: any) {
+ if (err.name === 'AbortError') {
+ return `Request to ${url} timed out after 15 seconds.`;
+ }
+ return `Error fetching ${url}: ${err.message}`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/channels/registry.ts b/src/channels/registry.ts
index f89ac0bd..9768c541 100644
--- a/src/channels/registry.ts
+++ b/src/channels/registry.ts
@@ -52,6 +52,14 @@ export class ChannelRegistry {
.map(([type]) => type);
}
+ getNotificationChannel(): Channel | undefined {
+ const telegram = this.channels.get('telegram');
+ if (telegram?.isReady()) return telegram;
+ const cli = this.channels.get('cli');
+ if (cli?.isReady()) return cli;
+ return this.channels.values().next().value;
+ }
+
private incomingHandler?: (msg: ChannelMessage) => void;
onIncomingMessage(handler: (msg: ChannelMessage) => void): void {
diff --git a/src/core/agent.ts b/src/core/agent.ts
index bac1c0c7..b0819b69 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -109,7 +109,18 @@ export class Agent {
}
try {
- const provider = this.providers.getDefault();
+ if (this.tokenBudget.isOverBudget()) {
+ const channel = this.channels.getChannelForMessage(msg);
+ if (channel && msg.channelType !== 'internal') {
+ await channel.send(
+ `I've exceeded my daily token budget (${this.tokenBudget.getStatusText()}). I'll be able to respond again after the budget resets tomorrow.`,
+ msg.channelId,
+ );
+ }
+ this.lifecycle.transition('idle');
+ return;
+ }
+
const systemPrompt = this.buildSystemPrompt();
const recentMemory = this.shortTerm.getRecent(msg.channelId, 10);
const relevantFacts = this.longTerm.search(msg.content, 3);
@@ -142,30 +153,59 @@ export class Agent {
await channel.typing(msg.channelId).catch(() => {});
}
- logger.info({ provider: provider.name, model: provider.getModel(), steps: MAX_STEPS }, 'Generating agentic response');
+ const fallbackIterator = this.providers.getFallbackIterator();
+ let result: any = null;
+ let usedProvider: { name: string; model: string } | null = null;
+ let lastError: any = null;
+
+ for (const provider of fallbackIterator) {
+ try {
+ logger.info({ provider: provider.name, model: provider.getModel(), steps: MAX_STEPS }, 'Generating agentic response');
+
+ result = await generateText({
+ model: provider.getModelInstance(),
+ system: systemPrompt,
+ messages,
+ tools: this.capabilities.getTools(),
+ maxSteps: MAX_STEPS,
+ onStepFinish: async ({ toolCalls, text }) => {
+ if (toolCalls && toolCalls.length > 0) {
+ const names = toolCalls.map((tc: any) => tc.toolName).join(', ');
+ logger.info({ tools: names }, 'Tool call step');
+ if (channel && msg.channelType !== 'internal') {
+ await channel.send(` [Using: ${names}]`, msg.channelId).catch(() => {});
+ }
+ }
+ },
+ });
- const result = await generateText({
- model: provider.getModelInstance(),
- system: systemPrompt,
- messages,
- tools: this.capabilities.getTools(),
- maxSteps: MAX_STEPS,
- onStepFinish: async ({ toolCalls, text }) => {
- if (toolCalls && toolCalls.length > 0) {
- const names = toolCalls.map((tc: any) => tc.toolName).join(', ');
- logger.info({ tools: names }, 'Tool call step');
- if (channel && msg.channelType !== 'internal') {
- await channel.send(` [Using: ${names}]`, msg.channelId).catch(() => {});
- }
+ usedProvider = { name: provider.name, model: provider.getModel() };
+ this.providers.markSuccess(provider.name);
+ break;
+ } catch (err: any) {
+ lastError = err;
+ logger.warn({ provider: provider.name, err: err.message }, 'Provider failed, trying fallback');
+ if (channel && msg.channelType !== 'internal') {
+ await channel.send(` [Provider ${provider.name} failed, trying fallback...]`, msg.channelId).catch(() => {});
}
- },
- });
+ }
+ }
+
+ if (!result) {
+ const errMsg = `All LLM providers failed. Last error: ${lastError?.message || 'unknown'}`;
+ logger.error({ err: lastError }, errMsg);
+ if (channel && msg.channelType !== 'internal') {
+ await channel.send(errMsg, msg.channelId);
+ }
+ this.lifecycle.transition('idle');
+ return;
+ }
const finalText = result.text;
this.tokenBudget.recordUsage({
- provider: provider.name,
- model: provider.getModel(),
+ provider: usedProvider!.name,
+ model: usedProvider!.model,
inputTokens: result.usage?.promptTokens ?? 0,
outputTokens: result.usage?.completionTokens ?? 0,
totalTokens: (result.usage?.promptTokens ?? 0) + (result.usage?.completionTokens ?? 0),
@@ -193,6 +233,12 @@ export class Agent {
channelType: msg.channelType,
});
+ if (msg.channelType !== 'internal') {
+ this.extractFacts(msg.content, finalText).catch(err => {
+ logger.warn({ err }, 'Fact extraction failed');
+ });
+ }
+
if (channel && msg.channelType !== 'internal') {
logger.info({ channelType: msg.channelType, targetId: msg.channelId }, 'Sending response');
const elapsed = Date.now() - startTime;
@@ -219,6 +265,11 @@ export class Agent {
if (skillContext) {
prompt += '\n\n' + skillContext;
}
+ const budgetStatus = this.tokenBudget.getStatusText();
+ prompt += '\n\n' + budgetStatus;
+ if (this.tokenBudget.getUsagePercentage() > 70) {
+ prompt += '\nBe concise to conserve tokens.';
+ }
return prompt;
}
@@ -258,6 +309,90 @@ export class Agent {
if (pruned > 0) {
logger.info({ pruned }, 'Episodic memory pruned');
}
+
+ const notifications: string[] = [];
+
+ const usagePct = this.tokenBudget.getUsagePercentage();
+ if (usagePct >= 80) {
+ notifications.push(`Token budget at ${Math.round(usagePct)}% — ${this.tokenBudget.getRemaining().toLocaleString()} tokens remaining today.`);
+ }
+
+ const pendingSchedules = this.scheduler.getManifests();
+ const now = Date.now();
+ for (const task of pendingSchedules) {
+ if (task.delaySeconds && task.executeAt) {
+ const executeAt = new Date(task.executeAt).getTime();
+ const diffMin = Math.round((executeAt - now) / 60000);
+ if (diffMin > 0 && diffMin <= 5) {
+ notifications.push(`Task "${task.description}" fires in ${diffMin} minute${diffMin !== 1 ? 's' : ''}.`);
+ }
+ }
+ }
+
+ if (notifications.length > 0) {
+ const channel = this.channels.getNotificationChannel();
+ if (channel) {
+ const msg = notifications.join('\n');
+ try {
+ await channel.send(msg, 'notification');
+ } catch (err) {
+ logger.warn({ err }, 'Failed to send heartbeat notification');
+ }
+ }
+ }
+ }
+
+ private async extractFacts(userMessage: string, agentResponse: string): Promise<void> {
+ const trivial = /^(hi|hello|hey|thanks|thank you|ok|okay|yes|no|bye|goodbye|good morning|good evening)\b/i;
+ if (trivial.test(userMessage.trim())) return;
+
+ if (!this.tokenBudget.canAfford(500)) return;
+
+ try {
+ const provider = this.providers.getDefault();
+ const result = await generateText({
+ model: provider.getModelInstance(),
+ system: 'You are a fact extractor. Read the conversation below and extract 1-3 important facts worth remembering long-term. Output each fact on a separate line, prefixed with "- ". Only extract facts that are specific, factual, and not obvious. If nothing is worth remembering, output nothing.',
+ messages: [
+ { role: 'user', content: `User: ${userMessage}\nAssistant: ${agentResponse}` },
+ ],
+ maxTokens: 200,
+ });
+
+ const text = result.text.trim();
+ if (!text) return;
+
+ const facts = text
+ .split('\n')
+ .map(l => l.replace(/^-\s*/, '').trim())
+ .filter(f => f.length > 10 && f.length < 200);
+
+ const existing = this.longTerm.getAll();
+ for (const fact of facts.slice(0, 3)) {
+ const isDupe = existing.some(e =>
+ e.fact.toLowerCase().includes(fact.toLowerCase().slice(0, 30))
+ );
+ if (!isDupe) {
+ this.longTerm.add({
+ topic: 'extracted',
+ fact,
+ source: 'conversation',
+ });
+ logger.info({ fact: fact.slice(0, 60) }, 'Fact extracted to long-term memory');
+ }
+ }
+
+ this.tokenBudget.recordUsage({
+ provider: provider.name,
+ model: provider.getModel(),
+ inputTokens: result.usage?.promptTokens ?? 0,
+ outputTokens: result.usage?.completionTokens ?? 0,
+ totalTokens: (result.usage?.promptTokens ?? 0) + (result.usage?.completionTokens ?? 0),
+ channelType: 'internal',
+ });
+ } catch (err) {
+ logger.warn({ err }, 'Fact extraction error');
+ }
}
async shutdown(): Promise<void> {
diff --git a/src/index.ts b/src/index.ts
index 556b649b..7e71a98f 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -153,7 +153,7 @@ async function runAgent(): Promise<void> {
const episodic = new EpisodicMemory(config);
const channels = new ChannelRegistry(config);
- const capabilities = new CapabilityRegistry(skillLoader, scheduler);
+ const capabilities = new CapabilityRegistry(skillLoader, scheduler, tokenBudget);
const agent = new Agent(
config, providers, identity, shortTerm, longTerm, episodic, channels, tokenBudget, capabilities, scheduler,
diff --git a/src/providers/registry.ts b/src/providers/registry.ts
index adfa4be9..e0b3f212 100644
--- a/src/providers/registry.ts
+++ b/src/providers/registry.ts
@@ -7,6 +7,7 @@ import { logger } from '../utils/logger.js';
export class ProviderRegistry {
private providers: Map<string, BaseProvider> = new Map();
private defaultName: string;
+ private lastSuccessful: string | null = null;
constructor(config: MercuryConfig) {
this.defaultName = config.providers.default;
@@ -37,6 +38,11 @@ export class ProviderRegistry {
}
getDefault(): BaseProvider {
+ if (this.lastSuccessful) {
+ const provider = this.providers.get(this.lastSuccessful);
+ if (provider) return provider;
+ }
+
const provider = this.providers.get(this.defaultName);
if (!provider) {
const first = this.providers.values().next().value;
@@ -46,6 +52,22 @@ export class ProviderRegistry {
return provider;
}
+ getFallbackIterator(): IterableIterator<BaseProvider> {
+ const ordered: BaseProvider[] = [];
+ const defaultProvider = this.getDefault();
+ ordered.push(defaultProvider);
+ for (const [, provider] of this.providers) {
+ if (provider !== defaultProvider) {
+ ordered.push(provider);
+ }
+ }
+ return ordered[Symbol.iterator]();
+ }
+
+ markSuccess(name: string): void {
+ this.lastSuccessful = name;
+ }
+
listAvailable(): string[] {
return [...this.providers.keys()];
}
diff --git a/src/utils/tokens.ts b/src/utils/tokens.ts
index b3b1c3d7..c3c14edc 100644
--- a/src/utils/tokens.ts
+++ b/src/utils/tokens.ts
@@ -1,4 +1,8 @@
+import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
+import { join } from 'node:path';
import type { MercuryConfig } from './config.js';
+import { getMercuryHome } from './config.js';
+import { logger } from './logger.js';
export interface TokenTracker {
dailyUsed: number;
@@ -17,14 +21,18 @@ export interface TokenLogEntry {
channelType: string;
}
+const TOKEN_FILE = 'token-usage.json';
+
export class TokenBudget {
private dailyUsed = 0;
private readonly dailyBudget: number;
private lastResetDate: string;
+ private requestLog: TokenLogEntry[] = [];
constructor(config: MercuryConfig) {
this.dailyBudget = config.tokens.dailyBudget;
this.lastResetDate = new Date().toISOString().split('T')[0];
+ this.restore();
}
canAfford(estimatedTokens: number): boolean {
@@ -32,9 +40,17 @@ export class TokenBudget {
return this.dailyUsed + estimatedTokens <= this.dailyBudget;
}
+ isOverBudget(): boolean {
+ this.resetIfNewDay();
+ return this.dailyUsed >= this.dailyBudget;
+ }
+
recordUsage(entry: Omit<TokenLogEntry, 'timestamp'>): void {
this.resetIfNewDay();
+ const logEntry: TokenLogEntry = { ...entry, timestamp: Date.now() };
this.dailyUsed += entry.totalTokens;
+ this.requestLog.push(logEntry);
+ this.persist();
}
getRemaining(): number {
@@ -47,11 +63,52 @@ export class TokenBudget {
return this.dailyBudget > 0 ? (this.dailyUsed / this.dailyBudget) * 100 : 0;
}
+ getStatusText(): string {
+ const pct = Math.round(this.getUsagePercentage());
+ const remaining = this.getRemaining();
+ return `Token budget: ${this.dailyUsed.toLocaleString()} / ${this.dailyBudget.toLocaleString()} used (${pct}%), ${remaining.toLocaleString()} remaining`;
+ }
+
private resetIfNewDay(): void {
const today = new Date().toISOString().split('T')[0];
if (today !== this.lastResetDate) {
this.dailyUsed = 0;
this.lastResetDate = today;
+ this.requestLog = [];
+ this.persist();
+ logger.info('Token budget reset for new day');
+ }
+ }
+
+ private persist(): void {
+ const path = join(getMercuryHome(), TOKEN_FILE);
+ try {
+ const data = {
+ dailyUsed: this.dailyUsed,
+ dailyBudget: this.dailyBudget,
+ lastResetDate: this.lastResetDate,
+ requestLog: this.requestLog.slice(-200),
+ };
+ writeFileSync(path, JSON.stringify(data, null, 2), 'utf-8');
+ } catch (err) {
+ logger.warn({ err }, 'Failed to persist token usage');
+ }
+ }
+
+ private restore(): void {
+ const path = join(getMercuryHome(), TOKEN_FILE);
+ if (!existsSync(path)) return;
+ try {
+ const raw = readFileSync(path, 'utf-8');
+ const data = JSON.parse(raw) as Partial<TokenTracker>;
+ const today = new Date().toISOString().split('T')[0];
+ if (data.lastResetDate === today) {
+ this.dailyUsed = data.dailyUsed ?? 0;
+ this.requestLog = data.requestLog ?? [];
+ }
+ this.lastResetDate = data.lastResetDate ?? today;
+ } catch (err) {
+ logger.warn({ err }, 'Failed to restore token usage');
}
}
}
\ No newline at end of file