Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix: harden budget tracking, permissions guardrails, and ask-me mode
Salman Qureshi077a3f50c9c8
diff --git a/package-lock.json b/package-lock.jsonindex f52b6350..7e2cb704 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "@cosmicstack/mercury-agent",- "version": "1.0.6",+ "version": "1.1.1","lockfileVersion": 2,"requires": true,"packages": {"": {"name": "@cosmicstack/mercury-agent",- "version": "1.0.6",+ "version": "1.1.1","license": "MIT","dependencies": {"@ai-sdk/anthropic": "^3.0.71",diff --git a/package.json b/package.jsonindex 27a2cd9f..77dbb788 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "@cosmicstack/mercury-agent",- "version": "1.1.0",+ "version": "1.1.1","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",diff --git a/src/capabilities/git/git-push.ts b/src/capabilities/git/git-push.tsindex ebc9aaea..209637a1 100644--- a/src/capabilities/git/git-push.ts+++ b/src/capabilities/git/git-push.ts@@ -13,11 +13,6 @@ export function createGitPushTool(permissions: PermissionManager, getCwd: () =>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}`;}diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.tsindex adb88693..8f17f40a 100644--- a/src/capabilities/permissions.ts+++ b/src/capabilities/permissions.ts@@ -151,7 +151,6 @@ export class PermissionManager {private askHandler?: (prompt: string) => Promise<string>;private autoApproveAll = false;private elevatedCommands: Set<string> = new Set();- private pendingApprovals: Set<string> = new Set();private currentChannelType: string = 'cli';private tempScopes: FileScope[] = [];@@ -206,14 +205,6 @@ export class PermissionManager {return this.elevatedCommands.has('run_command');}- addPendingApproval(baseCommand: string): void {- this.pendingApprovals.add(baseCommand);- }-- clearPendingApprovals(): void {- this.pendingApprovals.clear();- }-private load(): PermissionsManifest {if (existsSync(PERMISSIONS_FILE)) {try {@@ -281,6 +272,10 @@ export class PermissionManager {return { allowed: false, reason: `Permission denied: ${mode} access to ${path}` };}+ if (!this.autoApproveAll && this.askHandler && this.currentChannelType !== 'internal') {+ return this.requestScopeExternal(path, mode);+ }+return { allowed: false, reason: `Permission denied for ${mode} access to ${path}` };}@@ -301,12 +296,7 @@ export class PermissionManager {}const trimmed = command.trim();-const baseCmd = trimmed.split(/\s+/)[0];- if (this.pendingApprovals.has(baseCmd)) {- logger.info({ cmd: trimmed }, 'Shell command auto-approved (pending approval)');- return { allowed: true, needsApproval: false };- }for (const pattern of shell.blocked) {if (this.matchPattern(trimmed, pattern)) {@@ -333,7 +323,7 @@ export class PermissionManager {for (const pattern of shell.needsApproval) {if (this.matchPattern(trimmed, pattern)) {- if (this.currentChannelType === 'telegram' && this.askHandler) {+ if (this.askHandler && this.currentChannelType !== 'internal') {const result = await this.askHandler(`Run command: ${trimmed}`);if (result === 'yes') {return { allowed: true, needsApproval: false };@@ -348,7 +338,7 @@ export class PermissionManager {}}- if (this.currentChannelType === 'telegram' && this.askHandler) {+ if (this.askHandler && this.currentChannelType !== 'internal') {const result = await this.askHandler(`Run command: ${trimmed}`);if (result === 'yes') {return { allowed: true, needsApproval: false };@@ -466,6 +456,12 @@ export class PermissionManager {}private mergeDefaults(parsed: Partial<PermissionsManifest>): PermissionsManifest {+ const mergeArray = (existing: string[] | undefined, defaults: string[]): string[] => {+ if (!existing) return [...defaults];+ const combined = new Set([...defaults, ...existing]);+ return [...combined];+ };+return {capabilities: {filesystem: {@@ -474,9 +470,9 @@ export class PermissionManager {},shell: {enabled: parsed.capabilities?.shell?.enabled ?? DEFAULT_MANIFEST.capabilities.shell.enabled,- blocked: parsed.capabilities?.shell?.blocked ?? DEFAULT_MANIFEST.capabilities.shell.blocked,- autoApproved: parsed.capabilities?.shell?.autoApproved ?? DEFAULT_MANIFEST.capabilities.shell.autoApproved,- needsApproval: parsed.capabilities?.shell?.needsApproval ?? DEFAULT_MANIFEST.capabilities.shell.needsApproval,+ blocked: mergeArray(parsed.capabilities?.shell?.blocked, DEFAULT_MANIFEST.capabilities.shell.blocked),+ autoApproved: mergeArray(parsed.capabilities?.shell?.autoApproved, DEFAULT_MANIFEST.capabilities.shell.autoApproved),+ needsApproval: mergeArray(parsed.capabilities?.shell?.needsApproval, DEFAULT_MANIFEST.capabilities.shell.needsApproval),cwdOnly: parsed.capabilities?.shell?.cwdOnly ?? DEFAULT_MANIFEST.capabilities.shell.cwdOnly,},git: {diff --git a/src/capabilities/shell/run-command.ts b/src/capabilities/shell/run-command.tsindex f9c0568d..9a410fc2 100644--- a/src/capabilities/shell/run-command.ts+++ b/src/capabilities/shell/run-command.ts@@ -12,18 +12,13 @@ export function createRunCommandTool(permissions: PermissionManager, getCwd: ()description: `Run a shell command in the current working directory. Use the cd tool to change directories first — cd commands within this tool only affect chained commands (e.g., "cd /path && ls"), not subsequent calls.Blocked commands (sudo, rm -rf /, etc.) are never executed.Auto-approved commands (ls, cat, git status, curl, etc.) run without asking.-Other commands require user approval.`,+Other commands prompt the user for approval before execution.`,inputSchema: zodSchema(z.object({command: z.string().describe('The shell command to execute'),})),execute: async ({ command }) => {const check = await permissions.checkShellCommand(command);if (!check.allowed) {- if (check.needsApproval) {- const baseCmd = command.trim().split(/\s+/)[0];- permissions.addPendingApproval(baseCmd);- return `⚠ Command requires approval: ${command}\n\nTell the user what this command does and ask for permission. If they approve, try running it again. If they say "always", use the approve_command tool to permanently approve this command type.`;- }return `Error: ${check.reason}`;}diff --git a/src/core/agent.ts b/src/core/agent.tsindex fa832829..70a93608 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -1225,6 +1225,23 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub userreturn true;}+ if (cmd === '/permissions') {+ if (channelType === 'cli' && channel instanceof CLIChannel) {+ const mode = await channel.askPermissionMode?.();+ if (mode === 'allow-all') {+ this.capabilities.permissions.setAutoApproveAll(true);+ this.capabilities.permissions.addTempScope('/', true, true);+ await channel.send('Allow All mode active for this session. All scopes, commands, and loops auto-approved. Resets on restart.', channelId);+ } else {+ this.capabilities.permissions.setAutoApproveAll(false);+ await channel.send('Ask Me mode active. Risky actions will prompt for confirmation.', channelId);+ }+ return true;+ }+ await channel.send('Use /permissions in CLI to switch permission mode. On Telegram, use the /permissions button or command.', channelId);+ return true;+ }+if (cmd === '/status') {const config = ctx.config();const budget = ctx.tokenBudget();@@ -1522,9 +1539,11 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub userawait channel.withMenu(async (select) => {while (true) {const streamLabel = this.telegramStreaming ? 'Disable Telegram Streaming' : 'Enable Telegram Streaming';+ const permLabel = this.capabilities.permissions.isAutoApproveAll() ? 'Switch to Ask Me' : 'Switch to Allow All';const action = await select('Mercury Commands', [{ value: 'status', label: 'Status' },{ value: 'memory', label: 'Memory' },+ { value: 'permissions', label: permLabel },{ value: 'telegram', label: 'Telegram' },{ value: 'tools', label: 'Tools' },{ value: 'skills', label: 'Skills' },@@ -1551,6 +1570,11 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub usercontinue;}+ if (action === 'permissions') {+ await this.handleChatCommand('/permissions', 'cli', channelId);+ continue;+ }+if (action === 'telegram') {await this.openCliTelegramMenu(channel, channelId, select);continue;diff --git a/src/utils/tokens.ts b/src/utils/tokens.tsindex dcbc1946..1ac78f10 100644--- a/src/utils/tokens.ts+++ b/src/utils/tokens.ts@@ -23,6 +23,12 @@ export interface TokenLogEntry {const TOKEN_FILE = 'token-usage.json';+function safeNumber(value: any): number {+ if (value === null || value === undefined) return 0;+ const n = Number(value);+ return isNaN(n) ? 0 : n;+}+export class TokenBudget {private dailyUsed = 0;private dailyBudget: number;@@ -38,7 +44,7 @@ export class TokenBudget {canAfford(estimatedTokens: number): boolean {this.resetIfNewDay();- return this.dailyUsed + estimatedTokens <= this.dailyBudget;+ return safeNumber(this.dailyUsed) + estimatedTokens <= safeNumber(this.dailyBudget);}isOverBudget(): boolean {@@ -47,7 +53,7 @@ export class TokenBudget {this.forceNext = false;return false;}- return this.dailyUsed >= this.dailyBudget;+ return safeNumber(this.dailyUsed) >= safeNumber(this.dailyBudget);}forceAllowNext(): void {@@ -81,20 +87,26 @@ export class TokenBudget {recordUsage(entry: Omit<TokenLogEntry, 'timestamp'>): void {this.resetIfNewDay();- const logEntry: TokenLogEntry = { ...entry, timestamp: Date.now() };- this.dailyUsed += entry.totalTokens;+ const inputTokens = safeNumber(entry.inputTokens);+ const outputTokens = safeNumber(entry.outputTokens);+ const totalTokens = safeNumber(entry.totalTokens) || inputTokens + outputTokens;+ const safeEntry = { ...entry, inputTokens, outputTokens, totalTokens };+ const logEntry: TokenLogEntry = { ...safeEntry, timestamp: Date.now() };+ this.dailyUsed += totalTokens;this.requestLog.push(logEntry);this.persist();}getRemaining(): number {this.resetIfNewDay();- return Math.max(0, this.dailyBudget - this.dailyUsed);+ return Math.max(0, safeNumber(this.dailyBudget) - safeNumber(this.dailyUsed));}getUsagePercentage(): number {this.resetIfNewDay();- return this.dailyBudget > 0 ? (this.dailyUsed / this.dailyBudget) * 100 : 0;+ const budget = safeNumber(this.dailyBudget);+ const used = safeNumber(this.dailyUsed);+ return budget > 0 ? (used / budget) * 100 : 0;}getStatusText(): string {@@ -137,8 +149,16 @@ export class TokenBudget {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 ?? [];+ const restored = safeNumber(data.dailyUsed);+ if (!isNaN(restored)) {+ this.dailyUsed = restored;+ }+ this.requestLog = (data.requestLog ?? []).map((entry: any) => ({+ ...entry,+ inputTokens: safeNumber(entry.inputTokens),+ outputTokens: safeNumber(entry.outputTokens),+ totalTokens: safeNumber(entry.totalTokens),+ }));}this.lastResetDate = data.lastResetDate ?? today;} catch (err) {