Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat: Token Saver Mode + bottom status bar overhaul + per-step spinners (#69)
Salman Qureshi2f2c87018dc8
diff --git a/anonymous-file-uploader/SKILL.md b/anonymous-file-uploader/SKILL.mdnew file mode 100644index 00000000..465ceaf9--- /dev/null+++ b/anonymous-file-uploader/SKILL.md@@ -0,0 +1,154 @@+---+name: anonymous-file-uploader+description: Upload files to anonymous file sharing services without registration. Supports tmpfiles.org, 0x0.st, file.io, temp.sh, uguu.se, and more. Handles upload, verification, expiry tracking, and backup mirroring.+---++# Anonymous File Uploader Skill++Upload files to free, no-registration file sharing services. Supports automatic fallback between multiple providers and optional mirroring for redundancy.++## When to Use++- User says "upload this file somewhere and share the link"+- User wants to share a file anonymously+- User says "send this to a temp file host"+- User provides a file path and wants an anonymous download link+- Any request involving: `tmpfiles.org`, `0x0.st`, `file.io`, `temp.sh`, `uguu.se`, `catbox.moe`, `litterbox.catbox.moe`, `anonfiles.com`++## Supported Services++| Service | Max Size | Expiry | Method | Reliability |+|---------|----------|--------|--------|-------------|+| tmpfiles.org | 1GB | ~1 hour (free) | `curl -F "file=@FILE" https://tmpfiles.org/api/v1/upload` | ★★★★☆ |+| 0x0.st | 512MB | 30 days | `curl -F "file=@FILE" https://0x0.st` | ★★★☆☆ (occasional downtime) |+| file.io | 2GB | 1 download or 24h | `curl -F "file=@FILE" https://file.io` | ★★★☆☆ (rate limits) |+| temp.sh | 10GB | 14 days | `curl -F "file=@FILE" https://temp.sh/upload` | ★★★★☆ |+| uguu.se | 8GB | 60 days | `curl -F "files[]=@FILE" https://uguu.se/upload` | ★★★★☆ |+| catbox.moe | 200MB | Permanent | `curl -F "reqtype=fileupload" -F "fileToUpload=@FILE" https://catbox.moe/user/api.php` | ★★★★★ |+| litterbox | 1GB | 24h max | `curl -F "reqtype=fileupload" -F "time=24h" -F "fileToUpload=@FILE" https://litterbox.catbox.moe/resources/internals/api.php` | ★★★★☆ |+| anonfiles.com | 20GB | 30 days | `curl -F "file=@FILE" https://api.anonfiles.com/upload` | ★★★☆☆ (ads) |++## Workflow++### 1. Check File Exists++```bash+ls -lh <filepath>+```++If the file doesn't exist, inform the user and stop.++### 2. Choose Service(s)++**Single upload (default):** Start with `tmpfiles.org` — it's the simplest and most reliable.++```bash+RESPONSE=$(curl -s -F "file=@<filepath>" https://tmpfiles.org/api/v1/upload)+echo "$RESPONSE"+```++Extract the download URL:+```bash+DOWNLOAD_URL=$(echo "$RESPONSE" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['url'])")+```++**Fallback chain** (if tmpfiles.org fails):+1. Try `catbox.moe` (permanent, very reliable)+2. Try `uguu.se` (generous limits, 60 days)+3. Try `temp.sh` (10GB, 14 days)++### 3. Verify Upload++After uploading, verify the download URL is accessible:++```bash+curl -s -o /dev/null -w "%{http_code}" "<DOWNLOAD_URL>"+```++Should return `200`. If not, try the next service in the fallback chain.++### 4. Report Results++Present to the user:++```+✅ File uploaded successfully!+📎 Download: <URL>+⏱ Expiry: <expiry info>+📦 Size: <human-readable size>+🔄 Service: <service name>++Mirror (optional): <backup URL>+```++### 5. Mirroring (Optional)++For important files, offer to upload to a second service as a backup:++```+curl -F "file=@<filepath>" https://<BACKUP_SERVICE_URL>+```++### Mirror Upload Commands++**Catbox (permanent):**+```bash+curl -s -F "reqtype=fileupload" -F "fileToUpload=@<filepath>" https://catbox.moe/user/api.php+```++**Uguu (60 days):**+```bash+curl -s -F "files[]=@<filepath>" https://uguu.se/upload+```++**Temp.sh (14 days):**+```bash+curl -s -F "file=@<filepath>" https://temp.sh/upload+```++## Common Issues & Solutions++### "File not found" error+- Check the path exists with `ls -lh <path>`+- Expand `~` to the full home directory path+- The file might have been deleted since creation++### Upload returns empty response+- File might be too large for the service+- Try a different service with higher limits+- Check internet connectivity++### tmpfiles.org returns error+- Service is rate-limited or temporarily down+- Fall back to catbox.moe or uguu.se immediately++### File contains special characters+- curl handles this fine with `-F "file=@FILE"` syntax+- Spaces in filenames work without quoting issues++## Tips++- **Larger files** (>100MB): Use temp.sh (10GB limit, 14 days)+- **Permanent hosting** (<200MB): Use catbox.moe+- **Quick share** (<1GB): Use tmpfiles.org+- **Self-destructing** (1 download): Use file.io+- **Temporary** (<24h): Use litterbox.catbox.moe++## Response Template++When delivering the link to the user, format it cleanly:++```+📎 **<filename>** uploaded to <service>++🔗 <download_url>+⏳ Expires: <expiry_info>+📦 <size> | 🛡️ No registration required++<optional: mirror info>+```++## Dependencies++- `curl` (pre-installed on macOS/Linux)+- No API keys, no accounts, no registration neededdiff --git a/src/channels/cli.ts b/src/channels/cli.tsindex 63a8a5be..c3084af9 100644--- a/src/channels/cli.ts+++ b/src/channels/cli.ts@@ -2,12 +2,12 @@ import React from 'react';import { render } from 'ink';import fs from 'node:fs';import path from 'node:path';-import { execSync } from 'node:child_process';+import { execSync, execFile } from 'node:child_process';import type { ChannelMessage } from '../types/channel.js';import { BaseChannel, type PermissionMode } from './base.js';import { logger } from '../utils/logger.js';import { formatToolStep, formatToolResult } from '../utils/tool-label.js';-import type { ChatMessage, CompletionMeta, ToolStep, PermissionPromptState, SidebarSection, SkillInfo, SubAgentInfo, ProviderInfo, TokenInfo, AppMode, WorkspaceState, WorkspaceTreeNode, WorkspaceGitFile, BackgroundTaskInfo } from '../ui/types.js';+import type { ChatMessage, CompletionMeta, ToolStep, PermissionPromptState, SidebarSection, SkillInfo, SubAgentInfo, ProviderInfo, TokenInfo, SaverInfo, AppMode, WorkspaceState, WorkspaceTreeNode, WorkspaceGitFile, BackgroundTaskInfo } from '../ui/types.js';import { TuiApp } from '../ui/App.js';export interface TuiState {@@ -30,6 +30,7 @@ export interface TuiState {workspace: WorkspaceState | null;backgroundTasks: BackgroundTaskInfo[];web: { enabled: boolean; port: number } | null;+ saverInfo: SaverInfo | null;}const defaultState: TuiState = {@@ -52,8 +53,25 @@ const defaultState: TuiState = {workspace: null,backgroundTasks: [],web: null,+ saverInfo: null,};+function shallowEqualSubAgents(a: SubAgentInfo[], b: SubAgentInfo[]): boolean {+ if (a.length !== b.length) return false;+ for (let i = 0; i < a.length; i++) {+ if (a[i].id !== b[i].id || a[i].status !== b[i].status || a[i].progress !== b[i].progress) return false;+ }+ return true;+}++function shallowEqualBgTasks(a: BackgroundTaskInfo[], b: BackgroundTaskInfo[]): boolean {+ if (a.length !== b.length) return false;+ for (let i = 0; i < a.length; i++) {+ if (a[i].id !== b[i].id || a[i].status !== b[i].status || a[i].runningMs !== b[i].runningMs) return false;+ }+ return true;+}+export class CLIChannel extends BaseChannel {readonly type = 'cli' as const;private agentName: string;@@ -68,6 +86,14 @@ export class CLIChannel extends BaseChannel {private state: TuiState = { ...defaultState };private spotifyClient: any = null;private rawModeWatchdog: NodeJS.Timeout | null = null;+ private statusPoller: NodeJS.Timeout | null = null;+ private statusPollerBusy = false;+ private statusProviders: {+ tokens?: () => { used: number; budget: number; percentage: number };+ saver?: () => { state: import('../core/saver-mode.js').SaverModeState; savedToday: number; savedLifetime: number };+ subAgents?: () => SubAgentInfo[];+ bgTasks?: () => BackgroundTaskInfo[];+ } = {};constructor(agentName: string = 'Mercury') {super();@@ -87,6 +113,7 @@ export class CLIChannel extends BaseChannel {async stop(): Promise<void> {this.stopRawModeWatchdog();+ this.stopStatusPoller();this.inkInstance?.unmount();this.inkInstance = null;this.releaseRawMode();@@ -251,6 +278,12 @@ export class CLIChannel extends BaseChannel {this.update({ viewMode: this.state.viewMode === 'balanced' ? 'detailed' : 'balanced' });return;}+ // Clear stale tool steps from the previous task so the activity+ // panel starts fresh for each new user message.+ if (this.state.toolSteps.length > 0) {+ this.update({ toolSteps: [] });+ this.stepCount = 0;+ }onInput(trimmed);};@@ -547,6 +580,15 @@ export class CLIChannel extends BaseChannel {this.update({ tokenInfo: { used, budget, percentage } });}+ setSaverMode(state: import('../core/saver-mode.js').SaverModeState, savedToday: number, savedLifetime: number): void {+ if (state === 'off' && savedToday === 0 && savedLifetime === 0) {+ // Keep null to preserve zero-impact UI when saver has never been touched.+ this.update({ saverInfo: null });+ return;+ }+ this.update({ saverInfo: { state, savedToday, savedLifetime } });+ }+setWebInfo(enabled: boolean, port: number): void {this.update({ web: { enabled, port } });}@@ -588,6 +630,120 @@ export class CLIChannel extends BaseChannel {this.update({ workspace });}+ /**+ * Register provider callbacks the poller will sample on every tick.+ * Called once at boot from index.ts. Each callback should be cheap+ * (just a getter on already-in-memory state).+ */+ setStatusProviders(providers: typeof this.statusProviders): void {+ this.statusProviders = { ...this.statusProviders, ...providers };+ }++ /**+ * Start the 2s status poller. Refreshes:+ * - token budget bar (every tick)+ * - saver mode state (every tick)+ * - sub-agent counts (every tick)+ * - background task counts (every tick)+ * - workspace git state (every tick, async, only if workspace is active)+ *+ * Each section diff-checks its values before calling update() so+ * idle ticks cause zero React re-renders.+ */+ startStatusPoller(intervalMs = 2000): void {+ this.stopStatusPoller();+ this.statusPoller = setInterval(() => { void this.statusPollerTick(); }, intervalMs);+ // Fire once immediately so the first paint is fresh.+ void this.statusPollerTick();+ }++ stopStatusPoller(): void {+ if (this.statusPoller) {+ clearInterval(this.statusPoller);+ this.statusPoller = null;+ }+ }++ private async statusPollerTick(): Promise<void> {+ // Re-entrancy guard: if a previous git read is still in flight we skip.+ if (this.statusPollerBusy) return;+ this.statusPollerBusy = true;+ try {+ const patch: Partial<TuiState> = {};++ // 1. Token budget+ if (this.statusProviders.tokens) {+ const t = this.statusProviders.tokens();+ const cur = this.state.tokenInfo;+ if (!cur || cur.used !== t.used || cur.budget !== t.budget || cur.percentage !== t.percentage) {+ patch.tokenInfo = { used: t.used, budget: t.budget, percentage: t.percentage };+ }+ }++ // 2. Saver mode+ if (this.statusProviders.saver) {+ const s = this.statusProviders.saver();+ const cur = this.state.saverInfo;+ const shouldShow = !(s.state === 'off' && s.savedToday === 0 && s.savedLifetime === 0);+ if (!shouldShow) {+ if (cur !== null) patch.saverInfo = null;+ } else if (!cur || cur.state !== s.state || cur.savedToday !== s.savedToday || cur.savedLifetime !== s.savedLifetime) {+ patch.saverInfo = { state: s.state, savedToday: s.savedToday, savedLifetime: s.savedLifetime };+ }+ }++ // 3. Sub-agents+ if (this.statusProviders.subAgents) {+ const agents = this.statusProviders.subAgents();+ if (!shallowEqualSubAgents(this.state.subAgents, agents)) {+ patch.subAgents = agents;+ }+ }++ // 4. Background tasks+ if (this.statusProviders.bgTasks) {+ const tasks = this.statusProviders.bgTasks();+ if (!shallowEqualBgTasks(this.state.backgroundTasks, tasks)) {+ patch.backgroundTasks = tasks;+ }+ }++ // 5. Workspace git state (async — branch/files/ahead/behind can+ // change from outside Mercury, so we re-read every tick)+ if (this.state.workspace?.active) {+ const root = this.state.workspace.rootPath;+ const fresh = await this.readGitStateAsync(root);+ const cur = this.state.workspace;+ if (+ cur.branch !== fresh.branch ||+ cur.ahead !== fresh.ahead ||+ cur.behind !== fresh.behind ||+ cur.stagedCount !== fresh.stagedCount ||+ cur.unstagedCount !== fresh.unstagedCount ||+ cur.gitFiles.length !== fresh.files.length+ ) {+ patch.workspace = {+ ...cur,+ branch: fresh.branch,+ ahead: fresh.ahead,+ behind: fresh.behind,+ stagedCount: fresh.stagedCount,+ unstagedCount: fresh.unstagedCount,+ gitFiles: fresh.files,+ };+ }+ }++ if (Object.keys(patch).length > 0) {+ this.update(patch);+ }+ } catch {+ // Polling should never crash the UI loop.+ } finally {+ this.statusPollerBusy = false;+ }+ }+stageWorkspaceFile(filePath: string): { ok: boolean; message: string } {if (!this.state.workspace?.active) return { ok: false, message: 'No active workspace.' };const root = this.state.workspace.rootPath;@@ -705,7 +861,7 @@ export class CLIChannel extends BaseChannel {const nodes = this.buildTreeNodes(rootPath, expanded, 0);const selectedIndex = Math.max(0, nodes.findIndex((n) => n.path === selectedPath));const selectedNode = nodes[selectedIndex] || nodes[0] || null;- const { files, branch, stagedCount, unstagedCount } = this.readGitState(rootPath);+ const { files, branch, stagedCount, unstagedCount, ahead, behind } = this.readGitState(rootPath);return {active: true,rootPath,@@ -718,6 +874,8 @@ export class CLIChannel extends BaseChannel {stagedCount,unstagedCount,branch,+ ahead,+ behind,lastAction,codeScrollOffset: this.state.workspace?.codeScrollOffset ?? 0,focusArea: this.state.workspace?.focusArea ?? 'explorer',@@ -816,27 +974,61 @@ export class CLIChannel extends BaseChannel {return nodes;}- private readGitState(rootPath: string): { files: WorkspaceGitFile[]; branch: string; stagedCount: number; unstagedCount: number } {+ private readGitState(rootPath: string): { files: WorkspaceGitFile[]; branch: string; stagedCount: number; unstagedCount: number; ahead: number; behind: number } {try {const branch = execSync('git branch --show-current', { cwd: rootPath, stdio: 'pipe' }).toString().trim() || 'detached';- const out = execSync('git status --porcelain', { cwd: rootPath, stdio: 'pipe' }).toString();- const files: WorkspaceGitFile[] = out- .split('\n')- .map((line) => line.trimEnd())- .filter(Boolean)- .map((line) => {- const x = line[0] || ' ';- const y = line[1] || ' ';- const rel = line.slice(3).trim();- const staged = x !== ' ' && x !== '?';- const status = `${x}${y}`.trim() || '??';- return { path: rel, staged, status };- });- const stagedCount = files.filter((f) => f.staged).length;- const unstagedCount = files.length - stagedCount;- return { files, branch, stagedCount, unstagedCount };+ const out = execSync('git status --porcelain=v1 --branch', { cwd: rootPath, stdio: 'pipe' }).toString();+ return this.parseGitOutput(branch, out);+ } catch {+ return { files: [], branch: 'not-a-git-repo', stagedCount: 0, unstagedCount: 0, ahead: 0, behind: 0 };+ }+ }++ private parseGitOutput(branch: string, statusOut: string): { files: WorkspaceGitFile[]; branch: string; stagedCount: number; unstagedCount: number; ahead: number; behind: number } {+ const lines = statusOut.split('\n');+ let ahead = 0;+ let behind = 0;+ const header = lines[0] || '';+ const aheadMatch = header.match(/ahead (\d+)/);+ const behindMatch = header.match(/behind (\d+)/);+ if (aheadMatch) ahead = parseInt(aheadMatch[1], 10);+ if (behindMatch) behind = parseInt(behindMatch[1], 10);+ const files: WorkspaceGitFile[] = lines+ .slice(1)+ .map((line) => line.trimEnd())+ .filter(Boolean)+ .map((line) => {+ const x = line[0] || ' ';+ const y = line[1] || ' ';+ const rel = line.slice(3).trim();+ const staged = x !== ' ' && x !== '?';+ const status = `${x}${y}`.trim() || '??';+ return { path: rel, staged, status };+ });+ const stagedCount = files.filter((f) => f.staged).length;+ const unstagedCount = files.length - stagedCount;+ return { files, branch, stagedCount, unstagedCount, ahead, behind };+ }++ private execAsync(cmd: string, args: string[], cwd: string, timeoutMs = 1500): Promise<string> {+ return new Promise((resolve, reject) => {+ execFile(cmd, args, { cwd, timeout: timeoutMs, maxBuffer: 1024 * 512 }, (err, stdout) => {+ if (err) reject(err);+ else resolve(stdout.toString());+ });+ });+ }++ private async readGitStateAsync(rootPath: string): Promise<{ files: WorkspaceGitFile[]; branch: string; stagedCount: number; unstagedCount: number; ahead: number; behind: number }> {+ try {+ const [branchOut, statusOut] = await Promise.all([+ this.execAsync('git', ['branch', '--show-current'], rootPath),+ this.execAsync('git', ['status', '--porcelain=v1', '--branch'], rootPath),+ ]);+ const branch = branchOut.trim() || 'detached';+ return this.parseGitOutput(branch, statusOut);} catch {- return { files: [], branch: 'not-a-git-repo', stagedCount: 0, unstagedCount: 0 };+ return { files: [], branch: 'not-a-git-repo', stagedCount: 0, unstagedCount: 0, ahead: 0, behind: 0 };}}diff --git a/src/channels/telegram.ts b/src/channels/telegram.tsindex 0a66f150..852b15c3 100644--- a/src/channels/telegram.ts+++ b/src/channels/telegram.ts@@ -269,6 +269,7 @@ export class TelegramChannel extends BaseChannel {{ command: 'progress', description: 'Live status for the current task' },{ command: 'stop', description: 'Stop all agents and clear queue' },{ command: 'budget', description: 'Token budget status and management' },+ { command: 'saver', description: 'Toggle Token Saver Mode (save tokens, terser responses)' },{ command: 'stream', description: 'Toggle text streaming on/off' },{ command: 'memory', description: 'View and manage second brain memory' },{ command: 'permissions', description: 'Change permission mode (Ask Me / Allow All)' },diff --git a/src/core/agent.ts b/src/core/agent.tsindex 90ff758e..b5315885 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -15,6 +15,7 @@ import { ProviderRegistry as ProviderRegistryImpl } from '../providers/registry.import { Lifecycle } from './lifecycle.js';import { Scheduler } from './scheduler.js';import { ProgrammingMode } from './programming-mode.js';+import { SaverMode, NORMAL_HISTORY_WINDOW } from './saver-mode.js';import { BackgroundTaskManager } from './background-tasks.js';import { SkillBatcher } from '../skills/batcher.js';import type { SkillLoader } from '../skills/loader.js';@@ -295,6 +296,7 @@ export class Agent {private stepNarrative: import('../utils/tool-label.js').NarrativeStep[] = [];private supervisor?: import('../core/supervisor.js').SubAgentSupervisor;readonly programmingMode: ProgrammingMode;+ readonly saverMode: SaverMode;private spotifyClient?: SpotifyClient;private skillBatcher: SkillBatcher | null = null;private skillLoader?: SkillLoader;@@ -318,6 +320,7 @@ export class Agent {this.capabilities = capabilities;this.telegramStreaming = config.channels.telegram.streaming ?? true;this.programmingMode = new ProgrammingMode();+ this.saverMode = new SaverMode(config);this.backgroundTasks = new BackgroundTaskManager();this.backgroundTasks.onGlobalComplete((task) => {@@ -349,6 +352,7 @@ export class Agent {if (this.skillLoader) {this.skillBatcher = new SkillBatcher(supervisor, this.backgroundTasks);}+ supervisor.setSaverMode(this.saverMode);supervisor.setNotifyCallback(async (channelType, channelId, message) => {const channel = this.channels.get(channelType as any);if (channel) {@@ -964,8 +968,27 @@ export class Agent {return;}+ // Token Saver Mode auto-engagement check. When usage crosses the+ // configured threshold (default 75%), saver activates and the user+ // is notified once so they understand response style may change.+ {+ const transition = this.saverMode.evaluateAuto(this.tokenBudget.getUsagePercentage());+ if (transition.activated) {+ const notice = this.saverMode.consumeAutoActivationNotice();+ if (notice && msg.channelType !== 'internal') {+ const ch = this.channels.get(msg.channelType as any);+ if (ch) await ch.send(notice, msg.channelId).catch(() => {});+ }+ this.syncSaverToCli();+ } else if (transition.deactivated && msg.channelType !== 'internal') {+ const ch = this.channels.get(msg.channelType as any);+ if (ch) await ch.send('⚡ Token Saver Mode auto-disengaged (usage dropped). Normal response settings restored.', msg.channelId).catch(() => {});+ this.syncSaverToCli();+ }+ }+const systemPrompt = this.buildSystemPrompt();- const recentMemory = this.shortTerm.getRecent(msg.channelId, 10);+ const recentMemory = this.shortTerm.getRecent(msg.channelId, this.saverMode.adjustHistoryWindow(10));const messages: any[] = [];@@ -1201,6 +1224,12 @@ export class Agent {(tgChannel as TelegramChannel).beginTask(msg.channelId);}+ // Saver-mode-aware request limits. When saver is off these resolve to+ // the original constants (byte-identical to pre-saver behavior).+ const effectiveMaxOutputTokens = this.saverMode.adjustMaxOutputTokens(MAX_RESPONSE_TOKENS);+ const effectiveMaxSteps = this.saverMode.adjustMaxSteps(MAX_STEPS);+ const saverWasActive = this.saverMode.isActive();+for (const provider of fallbackIterator) {try {this.markProgress(`Calling ${provider.name}...`);@@ -1216,8 +1245,8 @@ export class Agent {system: systemPrompt,messages,tools: this.programmingMode.isPlan() ? this.capabilities.getPlanTools() : this.capabilities.getTools(),- maxOutputTokens: MAX_RESPONSE_TOKENS,- stopWhen: stepCountIs(MAX_STEPS),+ maxOutputTokens: effectiveMaxOutputTokens,+ stopWhen: stepCountIs(effectiveMaxSteps),abortSignal: loopAbortController.signal,...(deepseekProviderOptions ? { providerOptions: deepseekProviderOptions } : {}),onStepFinish: async ({ toolCalls, toolResults }) => {@@ -1459,8 +1488,8 @@ export class Agent {system: systemPrompt,messages,tools: this.programmingMode.isPlan() ? this.capabilities.getPlanTools() : this.capabilities.getTools(),- maxOutputTokens: MAX_RESPONSE_TOKENS,- stopWhen: stepCountIs(MAX_STEPS),+ maxOutputTokens: effectiveMaxOutputTokens,+ stopWhen: stepCountIs(effectiveMaxSteps),abortSignal: loopAbortController.signal,...(deepseekProviderOptions ? { providerOptions: deepseekProviderOptions } : {}),onStepFinish: async ({ toolCalls, toolResults }) => {@@ -1735,6 +1764,23 @@ export class Agent {totalTokens: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),channelType: msg.channelType,});+ this.syncTokenInfoToCli();++ // Estimate tokens saved by Saver Mode (cap headroom + history trim).+ // Rough: (default_cap - actual_output) when capped, plus history-window delta.+ if (saverWasActive) {+ const actualOutput = result.usage?.outputTokens ?? 0;+ const outputHeadroom = Math.max(0, MAX_RESPONSE_TOKENS - effectiveMaxOutputTokens);+ const outputSaved = Math.max(0, Math.min(outputHeadroom, MAX_RESPONSE_TOKENS - actualOutput));+ // Rough proxy: each trimmed history message ~120 tokens average.+ const historyTrimMessages = Math.max(0, NORMAL_HISTORY_WINDOW - this.saverMode.adjustHistoryWindow(NORMAL_HISTORY_WINDOW));+ const historySaved = historyTrimMessages * 120;+ const estimated = outputSaved + historySaved;+ if (estimated > 0) {+ this.tokenBudget.recordSavings(estimated);+ this.syncSaverToCli();+ }+ }this.shortTerm.add(msg.channelId, {id: msg.id,@@ -1867,6 +1913,10 @@ export class Agent {if (this.tokenBudget.getUsagePercentage() > 70) {prompt += '\nBe concise to conserve tokens.';}+ const saverSuffix = this.saverMode.getSystemPromptSuffix();+ if (saverSuffix) {+ prompt += saverSuffix;+ }const now = new Date();const dateStr = now.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });@@ -2090,6 +2140,7 @@ RULES:totalTokens: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),channelType: 'internal',});+ this.syncTokenInfoToCli();const text = result.text.trim();if (!text) return;@@ -2309,6 +2360,7 @@ Is this productive iteration or a stuck loop?`,await channel.send('Budget override applied — your next request will proceed.', channelId);} else if (action === 'reset' || action === '2') {this.tokenBudget.resetUsage();+ this.syncTokenInfoToCli();await channel.send(`Usage reset to zero. ${this.tokenBudget.getStatusText()}`, channelId);} else if (action === 'set' || action === '3') {const newBudget = parseInt(parts[1], 10);@@ -2317,6 +2369,7 @@ Is this productive iteration or a stuck loop?`,return;}this.tokenBudget.setBudget(newBudget);+ this.syncTokenInfoToCli();await channel.send(`Daily budget updated to ${newBudget.toLocaleString()} tokens. ${this.tokenBudget.getStatusText()}`, channelId);} else if (action === 'cancel' || action === '4') {await channel.send(`Cancelled. ${this.tokenBudget.getStatusText()}`, channelId);@@ -2327,6 +2380,144 @@ Is this productive iteration or a stuck loop?`,}}+ /**+ * Handle the /saver slash command — Token Saver Mode controls.+ * Subcommands: (empty)|status|on|off|toggle|threshold <n>|auto on|off|routing on|off|stats+ */+ async handleSaverCommand(subcommand: string, channelType: string, channelId: string): Promise<void> {+ const channel = this.channels.get(channelType as any);+ if (!channel) return;++ const parts = subcommand.trim().split(/\s+/).filter(Boolean);+ const action = (parts[0] || '').toLowerCase();+ const arg = (parts[1] || '').toLowerCase();++ const showStatus = async () => {+ const text = this.saverMode.getStatusText(+ this.tokenBudget.getSavedLifetime(),+ this.tokenBudget.getSavedToday(),+ );+ const usagePct = Math.round(this.tokenBudget.getUsagePercentage());+ await channel.send(`${text}\nCurrent daily usage: ${usagePct}%`, channelId);+ this.syncSaverToCli();+ };++ if (!action || action === 'status' || action === 'stats') {+ await showStatus();+ return;+ }++ if (action === 'on' || action === 'enable') {+ this.saverMode.enable();+ await channel.send(+ '⚡ Token Saver Mode enabled. Responses will be terser, step limits lower, and history window shorter to conserve tokens.',+ channelId,+ );+ this.syncSaverToCli();+ return;+ }++ if (action === 'off' || action === 'disable') {+ this.saverMode.disable();+ await channel.send('Token Saver Mode disabled. Normal response settings restored.', channelId);+ this.syncSaverToCli();+ return;+ }++ if (action === 'toggle') {+ const next = this.saverMode.toggle();+ await channel.send(+ next === 'on'+ ? '⚡ Token Saver Mode enabled.'+ : 'Token Saver Mode disabled.',+ channelId,+ );+ this.syncSaverToCli();+ return;+ }++ if (action === 'threshold') {+ const n = parseInt(parts[1], 10);+ if (isNaN(n) || n < 0 || n > 100) {+ await channel.send('Usage: /saver threshold <0-100> — percentage of daily budget at which saver auto-engages. Set 0 to disable.', channelId);+ return;+ }+ this.saverMode.setAutoThreshold(n);+ await channel.send(+ n === 0+ ? 'Saver auto-engage disabled (threshold set to 0).'+ : `Saver auto-engage threshold set to ${n}% of daily budget.`,+ channelId,+ );+ return;+ }++ if (action === 'auto') {+ if (arg === 'on' || arg === 'enable') {+ this.saverMode.setAutoEnabled(true);+ await channel.send(`Saver auto-engage enabled (at ${this.saverMode.getAutoThreshold()}% usage).`, channelId);+ } else if (arg === 'off' || arg === 'disable') {+ this.saverMode.setAutoEnabled(false);+ await channel.send('Saver auto-engage disabled. Saver will only activate when you run /saver on.', channelId);+ this.syncSaverToCli();+ } else {+ await channel.send(+ `Saver auto-engage is currently ${this.saverMode.isAutoEnabled() ? 'ON' : 'OFF'} (threshold: ${this.saverMode.getAutoThreshold()}%).\nUse /saver auto on|off to change.`,+ channelId,+ );+ }+ return;+ }++ if (action === 'routing') {+ if (arg === 'on' || arg === 'enable') {+ this.saverMode.setRoutingEnabled(true);+ await channel.send('Saver cheap-provider routing enabled (when saver is active, cheaper providers will be preferred).', channelId);+ } else if (arg === 'off' || arg === 'disable') {+ this.saverMode.setRoutingEnabled(false);+ await channel.send('Saver cheap-provider routing disabled.', channelId);+ } else {+ await channel.send(`Saver cheap-provider routing is currently ${this.saverMode.isRoutingEnabled() ? 'ON' : 'OFF'}.\nUse /saver routing on|off to change.`, channelId);+ }+ return;+ }++ await channel.send(+ 'Unknown saver command. Available:\n' ++ ' /saver — show status and savings\n' ++ ' /saver on — manually enable\n' ++ ' /saver off — disable\n' ++ ' /saver toggle — flip on/off\n' ++ ' /saver threshold <0-100> — auto-engage threshold (default 75)\n' ++ ' /saver auto on|off — enable/disable auto-engagement\n' ++ ' /saver routing on|off — prefer cheap providers while active (opt-in)',+ channelId,+ );+ }++ /** Push the current saver state to the CLI status bar if present. */+ private syncSaverToCli(): void {+ const ch = this.channels.get('cli');+ if (ch && (ch as any).setSaverMode) {+ (ch as any).setSaverMode(+ this.saverMode.getState(),+ this.tokenBudget.getSavedToday(),+ this.tokenBudget.getSavedLifetime(),+ );+ }+ }++ private syncTokenInfoToCli(): void {+ const ch = this.channels.get('cli');+ if (ch && (ch as any).setTokenInfo) {+ (ch as any).setTokenInfo(+ this.tokenBudget.getDailyUsed(),+ this.tokenBudget.getBudget(),+ Math.round(this.tokenBudget.getUsagePercentage()),+ );+ }+ }+private async handleSkillsSlashCommand(trimmed: string,channel: any,@@ -2536,6 +2727,11 @@ Is this productive iteration or a stuck loop?`,return true;}+ if (cmd === '/saver' || cmd.startsWith('/saver ')) {+ await this.handleSaverCommand(trimmed.slice('/saver'.length).trim(), channelType, channelId);+ return true;+ }+if (cmd.startsWith('/bg')) {await this.handleBgCommand(trimmed, { content: trimmed, channelId, channelType: channelType as any, id: Date.now().toString(36), senderId: 'user', timestamp: Date.now() }, channel);return true;@@ -2583,6 +2779,10 @@ Is this productive iteration or a stuck loop?`,if (cmd === '/status') {const config = ctx.config();const budget = ctx.tokenBudget();+ const saver = this.saverMode.getState();+ const saverLine = saver === 'off'+ ? `Saver: off (auto at ${this.saverMode.getAutoThreshold()}%)`+ : `Saver: ${saver.toUpperCase()} · saved today ~${this.tokenBudget.getSavedToday().toLocaleString()} tokens`;const lines = [`**${config.identity.name}** — Status`,`Owner: ${config.identity.owner || '(not set)'}`,@@ -2590,6 +2790,7 @@ Is this productive iteration or a stuck loop?`,`Telegram: ${config.channels.telegram.enabled ? 'enabled' : 'disabled'}`,`Telegram access: ${getTelegramAccessSummary(config)}`,`Budget: ${budget.getStatusText()}`,+ saverLine,`Skills: ${ctx.skillNames().length > 0 ? ctx.skillNames().join(', ') : 'none'}`,];await channel.send(lines.join('\n'), channelId);diff --git a/src/core/saver-mode.ts b/src/core/saver-mode.tsnew file mode 100644index 00000000..9d30fd67--- /dev/null+++ b/src/core/saver-mode.ts@@ -0,0 +1,242 @@+import { logger } from '../utils/logger.js';+import type { MercuryConfig } from '../utils/config.js';+import { saveConfig } from '../utils/config.js';++/**+ * Token Saver Mode — battery-saver-style optimization for LLM calls.+ *+ * States:+ * - 'off' : disabled; the agent runs with normal parameters.+ * - 'on' : user explicitly enabled saver mode.+ * - 'auto' : auto-engaged because daily usage crossed the threshold.+ *+ * When active, the agent reduces maxOutputTokens, step budget, history+ * window, and appends a "be terse" suffix to the system prompt. The user+ * is notified once on auto-engage so they understand response style may+ * change. Lifetime tokens saved are tracked separately on the TokenBudget.+ */+export type SaverModeState = 'off' | 'on' | 'auto';++export const SAVER_OUTPUT_TOKEN_RATIO = 0.4;+export const SAVER_STEP_RATIO = 0.5;+export const SAVER_HISTORY_WINDOW = 4;+export const NORMAL_HISTORY_WINDOW = 10;++export class SaverMode {+ private state: SaverModeState = 'off';+ /** Auto-engage threshold as a percentage (0-100). 0 disables auto. */+ private autoThreshold: number;+ /** Set to true once we've notified the user about this auto-activation. */+ private autoNotified = false;+ /** Per-session counter of follow-up reminder messages shown after activation. */+ private postActivationHints = 0;+ /** True when the user disables auto explicitly for this run. */+ private autoEnabled: boolean;+ /** Opt-in cheap-provider routing flag (off by default). */+ private routingEnabled = false;++ constructor(private config: MercuryConfig) {+ const cfg = config.tokens as any;+ this.autoThreshold = typeof cfg.saverAutoThreshold === 'number' ? cfg.saverAutoThreshold : 75;+ this.autoEnabled = cfg.saverAutoEnabled !== false; // default true+ if (cfg.saverMode === true) {+ this.state = 'on';+ }+ }++ /** Get current state. */+ getState(): SaverModeState {+ return this.state;+ }++ /** True when any saver optimization should apply. */+ isActive(): boolean {+ return this.state !== 'off';+ }++ /** True if user manually enabled (vs. auto-engaged). */+ isManual(): boolean {+ return this.state === 'on';+ }++ isAuto(): boolean {+ return this.state === 'auto';+ }++ getAutoThreshold(): number {+ return this.autoThreshold;+ }++ isAutoEnabled(): boolean {+ return this.autoEnabled;+ }++ isRoutingEnabled(): boolean {+ return this.routingEnabled && this.isActive();+ }++ /** Manually enable saver mode (persisted). */+ enable(): void {+ this.state = 'on';+ this.autoNotified = false;+ this.postActivationHints = 0;+ (this.config.tokens as any).saverMode = true;+ saveConfig(this.config);+ logger.info('Token Saver Mode: manually enabled');+ }++ /** Manually disable saver mode (also clears auto state; persisted). */+ disable(): void {+ this.state = 'off';+ this.autoNotified = false;+ this.postActivationHints = 0;+ (this.config.tokens as any).saverMode = false;+ saveConfig(this.config);+ logger.info('Token Saver Mode: disabled');+ }++ /** Cycle between off → on → off. */+ toggle(): SaverModeState {+ if (this.state === 'off') {+ this.enable();+ } else {+ this.disable();+ }+ return this.state;+ }++ /** Set auto-engage threshold (0-100). 0 disables auto. Persisted. */+ setAutoThreshold(percent: number): void {+ const clamped = Math.max(0, Math.min(100, Math.round(percent)));+ this.autoThreshold = clamped;+ (this.config.tokens as any).saverAutoThreshold = clamped;+ saveConfig(this.config);+ logger.info({ threshold: clamped }, 'Token Saver auto-threshold updated');+ }++ /** Toggle automatic engagement on the configured threshold. Persisted. */+ setAutoEnabled(enabled: boolean): void {+ this.autoEnabled = enabled;+ (this.config.tokens as any).saverAutoEnabled = enabled;+ saveConfig(this.config);+ // If auto is disabled and we were in auto state, drop back to off.+ if (!enabled && this.state === 'auto') {+ this.state = 'off';+ this.autoNotified = false;+ }+ logger.info({ enabled }, 'Token Saver auto-engage toggled');+ }++ setRoutingEnabled(enabled: boolean): void {+ this.routingEnabled = enabled;+ logger.info({ enabled }, 'Token Saver cheap-provider routing toggled');+ }++ /**+ * Re-evaluate auto-engage state based on current usage percent.+ * Returns true if a transition just happened (off→auto), so caller+ * can emit a one-time notification.+ */+ evaluateAuto(usagePercent: number): { activated: boolean; deactivated: boolean } {+ let activated = false;+ let deactivated = false;+ if (!this.autoEnabled || this.autoThreshold <= 0) {+ return { activated, deactivated };+ }+ // Manual 'on' takes precedence — auto logic doesn't touch it.+ if (this.state === 'on') {+ return { activated, deactivated };+ }+ if (this.state === 'off' && usagePercent >= this.autoThreshold) {+ this.state = 'auto';+ this.autoNotified = false;+ this.postActivationHints = 0;+ activated = true;+ logger.info({ usagePercent, threshold: this.autoThreshold }, 'Token Saver Mode auto-engaged');+ } else if (this.state === 'auto' && usagePercent < this.autoThreshold - 5) {+ // Hysteresis: drop out only after we're well below the threshold.+ this.state = 'off';+ this.autoNotified = false;+ this.postActivationHints = 0;+ deactivated = true;+ logger.info({ usagePercent }, 'Token Saver Mode auto-disengaged');+ }+ return { activated, deactivated };+ }++ /**+ * Returns the user-facing notification once per auto-activation.+ * Subsequent calls return null until the next activation.+ */+ consumeAutoActivationNotice(): string | null {+ if (this.state !== 'auto' || this.autoNotified) return null;+ this.autoNotified = true;+ return (+ `⚡ Token Saver Mode auto-enabled (${this.autoThreshold}% of daily budget reached). ` ++ `Responses may be shorter and step limits lower. Disable with /saver off.`+ );+ }++ /**+ * Returns a short follow-up reminder for the first couple of responses+ * after activation, then null. Helps make optimization transparent.+ */+ consumePostActivationHint(): string | null {+ if (!this.isActive()) return null;+ if (this.postActivationHints >= 2) return null;+ this.postActivationHints++;+ return '⚡ Saver active — response optimized for token efficiency.';+ }++ /** System-prompt suffix that nudges the model toward terse output. */+ getSystemPromptSuffix(): string {+ if (!this.isActive()) return '';+ const reason = this.state === 'auto'+ ? `(auto-engaged at ${this.autoThreshold}% of daily token budget)`+ : '(user-enabled)';+ return (+ `\n\n**TOKEN SAVER MODE IS ACTIVE** ${reason}` ++ `\n- Be terse. No preamble, no restatement of the request, no closing pleasantries.` ++ `\n- Prefer short answers — at most one short paragraph unless explicitly asked for detail.` ++ `\n- When showing code, show only the changed lines unless context is essential.` ++ `\n- Skip optional explanations. Skip "Let me ..." narration.` ++ `\n- Avoid speculative tool calls; act only when necessary.`+ );+ }++ /** Reduce max output tokens when active; otherwise return original. */+ adjustMaxOutputTokens(original: number): number {+ if (!this.isActive()) return original;+ return Math.max(256, Math.floor(original * SAVER_OUTPUT_TOKEN_RATIO));+ }++ /** Reduce max steps when active; otherwise return original. */+ adjustMaxSteps(original: number): number {+ if (!this.isActive()) return original;+ return Math.max(3, Math.floor(original * SAVER_STEP_RATIO));+ }++ /** Reduce short-term history window when active; otherwise return original. */+ adjustHistoryWindow(original: number): number {+ if (!this.isActive()) return original;+ return Math.min(original, SAVER_HISTORY_WINDOW);+ }++ /** Human-readable status text for /saver and /status output. */+ getStatusText(lifetimeSaved: number, todaySaved: number): string {+ const label = this.state === 'auto'+ ? `AUTO (engaged at ${this.autoThreshold}% usage)`+ : this.state === 'on'+ ? 'ON (manual)'+ : 'OFF';+ const auto = this.autoEnabled+ ? `auto-engage at ${this.autoThreshold}%`+ : 'auto-engage disabled';+ const routing = this.routingEnabled ? 'cheap-provider routing ON' : 'cheap-provider routing OFF';+ return (+ `Token Saver Mode: ${label}\n` ++ `Settings: ${auto}, ${routing}\n` ++ `Saved today: ~${todaySaved.toLocaleString()} tokens · Lifetime: ~${lifetimeSaved.toLocaleString()} tokens`+ );+ }+}diff --git a/src/core/sub-agent.ts b/src/core/sub-agent.tsindex 3de21cb6..bdf03e9a 100644--- a/src/core/sub-agent.ts+++ b/src/core/sub-agent.ts@@ -10,6 +10,7 @@ import type { TokenBudget } from '../utils/tokens.js';import type { CapabilityRegistry } from '../capabilities/registry.js';import type { FileLockManager } from './file-lock.js';import type { TaskBoard } from './task-board.js';+import type { SaverMode } from './saver-mode.js';import { logger } from '../utils/logger.js';export type ProgressCallback = (agentId: string, progress: string) => void;@@ -39,6 +40,7 @@ export class SubAgent {private tokenBudget: TokenBudget;private fileLockManager: FileLockManager;private taskBoard: TaskBoard;+ private saverMode?: SaverMode;private onProgress?: ProgressCallback;private onComplete?: CompletionCallback;@@ -60,6 +62,7 @@ export class SubAgent {tokenBudget: TokenBudget;fileLockManager: FileLockManager;taskBoard: TaskBoard;+ saverMode?: SaverMode;},) {this.config = config;@@ -76,6 +79,7 @@ export class SubAgent {this.tokenBudget = dependencies.tokenBudget;this.fileLockManager = dependencies.fileLockManager;this.taskBoard = dependencies.taskBoard;+ this.saverMode = dependencies.saverMode;}getStatus(): SubAgentStatus {@@ -145,7 +149,8 @@ export class SubAgent {try {const provider = this.providers.getDefault();- const maxSteps = this.config.maxSteps || 25;+ const baseMaxSteps = this.config.maxSteps || 25;+ const maxSteps = this.saverMode?.isActive() ? this.saverMode.adjustMaxSteps(baseMaxSteps) : baseMaxSteps;let stepsRemaining = maxSteps;logger.info({ agentId: this.config.id, provider: provider.name, maxSteps }, 'Sub-agent generating response');@@ -405,6 +410,10 @@ export class SubAgent {if (this.tokenBudget.getUsagePercentage() > 70) {prompt += '\nBe concise to conserve tokens.';}+ const saverSuffix = this.saverMode?.getSystemPromptSuffix() ?? '';+ if (saverSuffix) {+ prompt += saverSuffix;+ }prompt += `\n\nEnvironment:\n- Platform: ${process.platform}\n- Working directory: ${this.capabilities.getCwd()}`;diff --git a/src/core/supervisor.ts b/src/core/supervisor.tsindex 0d3e5cac..247c4684 100644--- a/src/core/supervisor.ts+++ b/src/core/supervisor.ts@@ -33,6 +33,7 @@ export class SubAgentSupervisor {private capabilities: CapabilityRegistry;private tokenBudget: TokenBudget;private channels: ChannelRegistry;+ private saverMode?: import('./saver-mode.js').SaverMode;private notifyCallback?: NotifyCallback;private lifecycleCallbacks: AgentLifecycleCallback[] = [];@@ -76,6 +77,11 @@ export class SubAgentSupervisor {this.notifyCallback = cb;}+ /** Inject SaverMode so spawned sub-agents inherit the user's saver preferences. */+ setSaverMode(saver: import('./saver-mode.js').SaverMode): void {+ this.saverMode = saver;+ }+setLifecycleCallback(cb: AgentLifecycleCallback): void {// Additive — don't overwrite previous callbacksthis.lifecycleCallbacks.push(cb);@@ -170,6 +176,7 @@ export class SubAgentSupervisor {tokenBudget: this.tokenBudget,fileLockManager: this.fileLockManager,taskBoard: this.taskBoard,+ saverMode: this.saverMode,});this.activeAgents.set(config.id, subAgent);diff --git a/src/index.ts b/src/index.tsindex 1117984d..30ad9365 100644--- a/src/index.ts+++ b/src/index.ts@@ -1496,7 +1496,31 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {bootCli.setSkills(skillInfos);bootCli.setProvider(getProviderLabel(defaultProvider), defaultModel);bootCli.setTokenInfo(tokenBudget.getDailyUsed(), tokenBudget.getBudget(), Math.round(tokenBudget.getUsagePercentage()));+ bootCli.setSaverMode(agent.saverMode.getState(), tokenBudget.getSavedToday(), tokenBudget.getSavedLifetime());bootCli.setWebInfo(config.web.enabled, config.web.port);+ // Wire live status providers so the bottom bar refreshes every 2s+ // without waiting for an LLM call or queue completion.+ bootCli.setStatusProviders({+ tokens: () => ({+ used: tokenBudget.getDailyUsed(),+ budget: tokenBudget.getBudget(),+ percentage: Math.round(tokenBudget.getUsagePercentage()),+ }),+ saver: () => ({+ state: agent.saverMode.getState(),+ savedToday: tokenBudget.getSavedToday(),+ savedLifetime: tokenBudget.getSavedLifetime(),+ }),+ subAgents: () => supervisor ? supervisor.getActiveAgents().map((a) => ({+ id: a.id,+ task: a.task,+ status: a.status,+ progress: a.progress,+ startedAt: 0,+ })) : [],+ bgTasks: () => agent.backgroundTasks.getAllSummaries(),+ });+ bootCli.startStatusPoller(2000);bootCli.mountTUI((inputText: string) => {bootCli.sendUserMessage(inputText);}, spotifyClient, () => {diff --git a/src/ui/App.tsx b/src/ui/App.tsxindex 59663c0e..df7df208 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -144,6 +144,15 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCli'/skills remove ','/skills help','/stream',+ '/saver',+ '/saver on',+ '/saver off',+ '/saver toggle',+ '/saver threshold ',+ '/saver auto on',+ '/saver auto off',+ '/saver routing on',+ '/saver routing off','/view','/view balanced','/view detailed',@@ -811,6 +820,7 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCli))}</Box>)}+ <TokenBarView state={state} /></Box>);}@@ -851,11 +861,6 @@ function BackgroundBarView({ tasks }: { tasks: BackgroundTaskInfo[] }) {function StatusBarView({ state }: { state: TuiState }) {const modeColor = state.programmingMode === 'execute' ? 'green' : state.programmingMode === 'plan' ? 'yellow' : 'gray';const modeLabel = state.programmingMode === 'off' ? '' : ` ${state.programmingMode.toUpperCase()}`;- let tokenBar = '';- if (state.tokenInfo) {- const filled = Math.min(20, Math.round(state.tokenInfo.percentage / 5));- tokenBar = `[${'█'.repeat(filled)}${'░'.repeat(20 - filled)}] ${state.tokenInfo.percentage}%`;- }const providerBadge = state.provider ? `⚡ ${state.provider.name} · ${state.provider.model}` : '⚡ No provider';const viewLabel = state.viewMode === 'balanced' ? 'minimal' : 'detailed';@@ -883,6 +888,9 @@ function StatusBarView({ state }: { state: TuiState }) {<Box flexGrow={1}><Text bold color="cyan">{state.agentName}</Text>{state.programmingMode !== 'off' && <Text> <Text color={modeColor} bold>{modeLabel}</Text></Text>}+ {state.saverInfo && state.saverInfo.state !== 'off' && (+ <Text> <Text color="gray">|</Text> <Text color={state.saverInfo.state === 'auto' ? 'yellow' : 'green'} bold>{`⚡SAVER${state.saverInfo.state === 'auto' ? ' (auto)' : ''}`}</Text></Text>+ )}{state.projectContext && <Text> <Text color="gray">|</Text> <Text color="blue">{state.projectContext}</Text></Text>}<Text> <Text color="gray">|</Text> <Text color="yellow">View: {viewLabel}</Text></Text><Text> <Text color="gray">|</Text> <Text color="green">{state.permissionMode === 'allow-all' ? '🔓' : '🔒'}</Text></Text>@@ -892,24 +900,110 @@ function StatusBarView({ state }: { state: TuiState }) {<Box paddingX={1}><Text color="gray">{'─'.repeat(50)}</Text></Box>- {state.tokenInfo && (- <Box paddingX={1}>- <Text color="cyan">Tokens </Text>- <Text>{tokenBar}</Text>- <Text color="gray"> {state.tokenInfo.used.toLocaleString()}/{state.tokenInfo.budget.toLocaleString()}</Text>- </Box>- )}</Box>);}+function TokenBarView({ state }: { state: TuiState }) {+ if (!state.tokenInfo && !state.provider) return null;++ const saverActive = !!(state.saverInfo && state.saverInfo.state !== 'off');+ const saverColor = state.saverInfo?.state === 'auto' ? 'yellow' : 'green';++ // Color the percentage based on usage thresholds (or saver state if active)+ const pct = state.tokenInfo?.percentage ?? 0;+ const pctColor = saverActive+ ? saverColor+ : pct >= 90 ? 'red' : pct >= 70 ? 'yellow' : 'cyan';++ // Sub-agent count (running only)+ const runningAgents = state.subAgents.filter((a) => a.status === 'running' || a.status === 'paused').length;+ // Background task count (running only)+ const runningBg = state.backgroundTasks.filter((t) => t.status === 'running').length;++ const isWorkspace = state.mode === 'workspace' && state.workspace;++ return (+ <Box flexDirection="column">+ <Box paddingX={1}>+ <Text color="gray">{'─'.repeat(50)}</Text>+ </Box>+ <Box paddingX={1} paddingBottom={0}>+ {state.tokenInfo && (+ <>+ {saverActive && (+ <Text color={saverColor} bold>⚡ </Text>+ )}+ <Text color={pctColor}>{pct < 25 ? '○' : pct < 50 ? '◔' : pct < 75 ? '◑' : pct < 100 ? '◕' : '●'} </Text>+ <Text color={pctColor}>+ [{'█'.repeat(Math.min(10, Math.round(pct / 10)))}{'░'.repeat(10 - Math.min(10, Math.round(pct / 10)))}]+ </Text>+ <Text color={pctColor} bold> {pct}%</Text>+ {saverActive && state.saverInfo!.savedToday > 0 && (+ <Text color="green"> · saved ~{formatCompact(state.saverInfo!.savedToday)}</Text>+ )}+ {saverActive && state.saverInfo!.savedToday === 0 && (+ <Text color={saverColor}> · SAVER</Text>+ )}+ </>+ )}++ {state.provider && (+ <>+ <Text color="gray"> │ </Text>+ <Text color="magenta">{state.provider.model}</Text>+ </>+ )}++ {isWorkspace && (+ <>+ <Text color="gray"> │ </Text>+ <Text color="blue">⎇ {state.workspace!.branch}</Text>+ {(state.workspace!.ahead > 0 || state.workspace!.behind > 0) && (+ <Text color="yellow">+ {state.workspace!.ahead > 0 ? ` ↑${state.workspace!.ahead}` : ''}+ {state.workspace!.behind > 0 ? ` ↓${state.workspace!.behind}` : ''}+ </Text>+ )}+ {(state.workspace!.stagedCount > 0 || state.workspace!.unstagedCount > 0) && (+ <Text color="gray">+ {state.workspace!.stagedCount > 0 ? <Text color="green"> S{state.workspace!.stagedCount}</Text> : null}+ {state.workspace!.unstagedCount > 0 ? <Text color="yellow"> M{state.workspace!.unstagedCount}</Text> : null}+ </Text>+ )}+ </>+ )}++ {!isWorkspace && runningBg > 0 && (+ <>+ <Text color="gray"> │ </Text>+ <Text color="cyan">⏳ {runningBg} bg</Text>+ </>+ )}+ {!isWorkspace && runningAgents > 0 && (+ <>+ <Text color="gray"> │ </Text>+ <Text color="magenta">🤖 {runningAgents} agent{runningAgents !== 1 ? 's' : ''}</Text>+ </>+ )}+ </Box>+ </Box>+ );+}++function formatCompact(n: number): string {+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;+ if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;+ return String(n);+}+function ChatBody({ state }: { state: TuiState }) {return (<Box flexDirection="row" flexGrow={1}>{state.sidebarSections.length > 0 && <SidebarView sections={state.sidebarSections} />}<Box flexDirection="column" flexGrow={1}><ChatMessagesView messages={state.chatMessages} agentName={state.agentName} />- {state.toolSteps.length > 0 && !state.isThinking && <ToolStepsView steps={state.toolSteps} viewMode={state.viewMode} />}+ {state.toolSteps.length > 0 && !state.isThinking && <ToolStepsView steps={state.toolSteps} viewMode={state.viewMode} idle />}{state.isThinking && <ThinkingIndicator agentName={state.agentName} steps={state.toolSteps} mode={state.mode} />}{state.subAgents.length > 0 && <AgentPanelView agents={state.subAgents} />}</Box>@@ -948,7 +1042,7 @@ function CodingBody({ state }: { state: TuiState }) {</Box><Box flexDirection="column" flexGrow={1}><ChatMessagesView messages={state.chatMessages} agentName={state.agentName} />- {state.toolSteps.length > 0 && !state.isThinking && <ToolStepsView steps={state.toolSteps} viewMode={state.viewMode} />}+ {state.toolSteps.length > 0 && !state.isThinking && <ToolStepsView steps={state.toolSteps} viewMode={state.viewMode} idle />}{state.isThinking && <ThinkingIndicator agentName={state.agentName} steps={state.toolSteps} mode={state.mode} />}<Box paddingX={1} marginTop={1}><Text dimColor>Mode shortcuts: Ctrl+P Plan · Ctrl+X Execute</Text>@@ -1575,7 +1669,23 @@ function RunningStepRow({ step }: { step: ToolStep }) {);}-function ToolStepsView({ steps, viewMode }: { steps: ToolStep[]; viewMode: 'balanced' | 'detailed' }) {+function ToolStepsView({ steps, viewMode, idle }: { steps: ToolStep[]; viewMode: 'balanced' | 'detailed'; idle?: boolean }) {+ // When idle (task complete), collapse to a single summary line to free+ // up screen space. Full history remains available via /progress.+ if (idle) {+ const last = [...steps].reverse().find((s) => s.status === 'done' || s.status === 'error') ?? steps[steps.length - 1];+ if (!last) return null;+ const totalDone = steps.filter((s) => s.status === 'done').length;+ const icon = last.status === 'done' ? '✅' : last.status === 'error' ? '❌' : '·';+ const more = totalDone > 1 ? ` · +${totalDone - 1} earlier` : '';+ return (+ <Box marginLeft={2} marginTop={1}>+ <Text dimColor>{icon} {last.label}{last.elapsed != null ? ` (${last.elapsed.toFixed(1)}s)` : ''}{more} · /progress</Text>+ </Box>+ );+ }++const visible = viewMode === 'detailed' ? steps.slice(-20) : steps.slice(-5);const totalDone = steps.filter((s) => s.status === 'done').length;const totalRunning = steps.filter((s) => s.status === 'running').length;diff --git a/src/ui/types.ts b/src/ui/types.tsindex 3e97f686..ca23e303 100644--- a/src/ui/types.ts+++ b/src/ui/types.ts@@ -1,4 +1,5 @@import type { ProgrammingModeState } from '../core/programming-mode.js';+import type { SaverModeState } from '../core/saver-mode.js';import type { SubAgentStatus } from '../types/agent.js';import type { PermissionMode } from '../channels/base.js';@@ -31,6 +32,8 @@ export interface WorkspaceState {stagedCount: number;unstagedCount: number;branch: string;+ ahead: number;+ behind: number;lastAction: string;codeScrollOffset: number;focusArea: 'explorer' | 'code' | 'git' | 'chat';@@ -107,6 +110,12 @@ export interface TokenInfo {percentage: number;}+export interface SaverInfo {+ state: SaverModeState;+ savedToday: number;+ savedLifetime: number;+}+export interface MercuryAppState {mode: AppMode;programmingMode: ProgrammingModeState;diff --git a/src/utils/config.ts b/src/utils/config.tsindex e78b8e55..0151ac43 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -111,6 +111,14 @@ export interface MercuryConfig {};tokens: {dailyBudget: number;+ /** When true, Token Saver Mode is manually enabled. Persisted. */+ saverMode?: boolean;+ /** Percentage of daily budget at which saver auto-engages (0 disables). */+ saverAutoThreshold?: number;+ /** Master switch for automatic engagement (defaults to true). */+ saverAutoEnabled?: boolean;+ /** Lifetime estimated tokens saved by saver mode (informational). */+ saverTokensSavedLifetime?: number;};subagents: {enabled: boolean;diff --git a/src/utils/manual.ts b/src/utils/manual.tsindex 233f3af4..fe71c3eb 100644--- a/src/utils/manual.ts+++ b/src/utils/manual.ts@@ -133,6 +133,13 @@ export function getManual(): string {['/stream', 'Toggle text streaming on/off (Telegram)'],['/stream on', 'Enable streaming (live text updates)'],['/stream off', 'Disable streaming (single message)'],+ ['/saver', 'Show Token Saver Mode status and tokens saved'],+ ['/saver on', 'Manually enable Token Saver Mode (terser, faster, cheaper)'],+ ['/saver off', 'Disable Token Saver Mode'],+ ['/saver toggle', 'Toggle Token Saver Mode on/off'],+ ['/saver threshold <0-100>', 'Auto-engage threshold (default 75%; 0 to disable)'],+ ['/saver auto on|off', 'Enable/disable automatic engagement at threshold'],+ ['/saver routing on|off', 'Prefer cheap providers when saver is active (opt-in)'],['/agents', 'List all sub-agents and their status'],['/agents stop <id|all>', 'Stop a sub-agent or all sub-agents'],['/agents pause <id>', 'Pause a running sub-agent'],@@ -269,6 +276,16 @@ export function getTelegramHelp(): string {lines.push('/budget set <n> — Set daily token budget');lines.push('');+ lines.push('**Token Saver**');+ lines.push('/saver — Show saver status and tokens saved');+ lines.push('/saver on — Manually enable Token Saver Mode');+ lines.push('/saver off — Disable Token Saver Mode');+ lines.push('/saver toggle — Toggle on/off');+ lines.push('/saver threshold <0-100> — Auto-engage threshold (default 75%)');+ lines.push('/saver auto on|off — Enable/disable automatic engagement');+ lines.push('/saver routing on|off — Prefer cheap providers while active (opt-in)');+ lines.push('');+lines.push('**Programming Mode**');lines.push('/code — Show current mode');lines.push('/code plan — Analyze and present options (no coding)');diff --git a/src/utils/tokens.ts b/src/utils/tokens.tsindex dfe6bd4a..34ac7c75 100644--- a/src/utils/tokens.ts+++ b/src/utils/tokens.ts@@ -37,10 +37,18 @@ export class TokenBudget {private requestLog: TokenLogEntry[] = [];private forceNext = false;private perAgentUsage: Map<string, number> = new Map();+ /** Estimated tokens saved today by saver mode (resets daily). */+ private dailySaved = 0;+ /** Cumulative lifetime estimated tokens saved (persisted). */+ private lifetimeSaved = 0;constructor(private config: MercuryConfig) {this.dailyBudget = config.tokens.dailyBudget;this.lastResetDate = new Date().toISOString().split('T')[0];+ const lifetime = (config.tokens as any).saverTokensSavedLifetime;+ if (typeof lifetime === 'number' && Number.isFinite(lifetime) && lifetime > 0) {+ this.lifetimeSaved = lifetime;+ }this.restore();}@@ -132,6 +140,34 @@ export class TokenBudget {return `Token budget: ${used.toLocaleString()} / ${this.dailyBudget.toLocaleString()} used (${pct}%), ${remaining.toLocaleString()} remaining`;}+ /**+ * Record an estimated savings from Token Saver Mode. Updates both the+ * per-day counter (resets at day rollover) and the lifetime counter+ * (persisted to mercury.yaml). Negative or zero values are ignored.+ */+ recordSavings(estimatedTokens: number): void {+ const n = safeNumber(estimatedTokens);+ if (n <= 0) return;+ this.resetIfNewDay();+ this.dailySaved += n;+ this.lifetimeSaved += n;+ try {+ (this.config.tokens as any).saverTokensSavedLifetime = this.lifetimeSaved;+ saveConfig(this.config);+ } catch (err) {+ logger.warn({ err }, 'Failed to persist saver lifetime counter');+ }+ }++ getSavedToday(): number {+ this.resetIfNewDay();+ return this.dailySaved;+ }++ getSavedLifetime(): number {+ return this.lifetimeSaved;+ }+private resetIfNewDay(): void {const today = new Date().toISOString().split('T')[0];if (today !== this.lastResetDate) {@@ -139,6 +175,7 @@ export class TokenBudget {this.lastResetDate = today;this.requestLog = [];this.perAgentUsage.clear();+ this.dailySaved = 0;this.persist();logger.info('Token budget reset for new day');}diff --git a/website/docs/cli-commands/in-chat-commands.mdx b/website/docs/cli-commands/in-chat-commands.mdxindex 4cb9300b..d7b41820 100644--- a/website/docs/cli-commands/in-chat-commands.mdx+++ b/website/docs/cli-commands/in-chat-commands.mdx@@ -38,6 +38,22 @@ Type these during a conversation with Mercury. Most work in both CLI and Telegra| `/budget reset` | Reset usage to zero || `/budget set <n>` | Change daily token budget |+## Token Saver Mode++A battery-saver-style mode that reduces token spend per request. When active, Mercury produces terser responses, runs fewer reasoning steps, and uses a shorter conversation history window. It also auto-engages at a configurable percentage of your daily budget.++| Command | Description |+|---------|-------------|+| `/saver` | Show saver status, today's savings, and lifetime savings |+| `/saver on` | Manually enable Token Saver Mode (persisted) |+| `/saver off` | Disable Token Saver Mode (also clears any auto-engagement) |+| `/saver toggle` | Toggle saver on/off |+| `/saver threshold <0-100>` | Set auto-engage threshold as a percentage of daily budget (default `75`, `0` disables auto) |+| `/saver auto on\|off` | Master switch for automatic engagement at threshold |+| `/saver routing on\|off` | Opt-in: prefer cheaper providers while saver is active |++When saver auto-engages, Mercury sends a one-time notification so you know responses may be shorter. Disable manually with `/saver off` or `/saver auto off`. See [Token Saver Mode reference](../reference/token-saver) for what changes when saver is active.+## Programming Mode| Command | Description |diff --git a/website/docs/reference/token-saver.mdx b/website/docs/reference/token-saver.mdxnew file mode 100644index 00000000..9e256a1d--- /dev/null+++ b/website/docs/reference/token-saver.mdx@@ -0,0 +1,133 @@+---+id: token-saver+title: Token Saver Mode+---++Token Saver Mode is a battery-saver-style optimization layer for LLM calls. When active, Mercury produces shorter, terser responses, runs fewer reasoning steps, and uses a smaller history window — saving tokens at the cost of some verbosity and exploration depth.++It is designed to **never affect behavior when disabled**. With saver `off`, every LLM call uses exactly the same parameters as a Mercury install without saver support.++## How It Works++When Token Saver Mode is active, Mercury changes four things about every LLM call:++| Lever | Default (off) | Saver active |+|-------|---------------|--------------|+| `maxOutputTokens` per response | `4096` | `1638` (× 0.4) |+| Step budget per request | `25` steps | `12` steps (÷ 2) |+| Recent-history window injected as context | `10` messages | `4` messages |+| System prompt suffix | (none) | "Be terse, no preamble, no restatement, …" |++A fifth lever — **cheap-provider routing** — is available as an opt-in (`/saver routing on`). When enabled while saver is active, Mercury reorders the provider fallback list to prefer cheaper providers first (e.g., DeepSeek and Ollama before Claude or GPT-4). It is off by default to avoid surprising provider switches mid-task.++These changes apply to both the main agent and any sub-agents the supervisor spawns.++## Three States++Saver mode has three states:++- **`off`** — disabled. Mercury runs with original parameters. Zero-impact.+- **`on`** — manually enabled. Persists across restarts.+- **`auto`** — automatically engaged because daily usage crossed the threshold. Resets to `off` automatically when usage drops well below the threshold (5-point hysteresis) or at the next daily-budget reset.++You can always force-disable auto with `/saver off` (one-shot) or `/saver auto off` (turns auto-engagement off permanently).++## Auto-Engagement++By default, saver auto-engages at **75%** of your daily token budget. When that happens, Mercury sends a one-time notice to the active channel so you know response style is about to change:++> ⚡ Token Saver Mode auto-enabled (75% of daily budget reached). Responses may be shorter and step limits lower. Disable with `/saver off`.++If usage drops below 70% (the threshold minus 5-point hysteresis), saver auto-disengages and sends a corresponding notification.++You can change the threshold or disable auto-engagement entirely:++```text+/saver threshold 80 # auto-engage at 80% instead of 75%+/saver threshold 0 # disable auto-engagement (equivalent to /saver auto off)+/saver auto off # disable auto-engagement (preserves threshold value)+```++## Slash Commands++| Command | Description |+|---------|-------------|+| `/saver` | Show saver status, today's savings, and lifetime savings |+| `/saver on` | Manually enable saver (persisted) |+| `/saver off` | Disable saver (also clears any auto-engagement state) |+| `/saver toggle` | Flip saver on/off |+| `/saver threshold <0-100>` | Set auto-engage threshold as a percentage of daily budget |+| `/saver auto on\|off` | Master switch for automatic engagement at threshold |+| `/saver routing on\|off` | Opt-in: prefer cheap providers while saver is active |++All commands work on both CLI and Telegram.++## Status Display++When saver is active, the CLI status bar shows a colored `⚡SAVER` badge next to the agent name:++- **Green** `⚡SAVER` — manually enabled (`/saver on`)+- **Yellow** `⚡SAVER (auto)` — auto-engaged at threshold++The token usage bar gains a `· saved ~N` suffix showing today's estimated savings. The `/status` command also includes a saver line.++## Tokens Saved — Estimation++Mercury keeps two counters:++- **Saved today** — estimated tokens saved since midnight (resets at daily-budget rollover)+- **Saved lifetime** — cumulative estimate across all time, persisted to `~/.mercury/mercury.yaml`++Estimation per request is rough but transparent:++```+saved = output_headroom + history_trim_estimate++output_headroom = min(MAX_RESPONSE_TOKENS - effective_cap,+ MAX_RESPONSE_TOKENS - actual_output_tokens)+history_trim = (normal_window - saver_window) × 120 tokens/message+```++Treat these numbers as guidance — they are not exact, since the actual savings depend on how short the model chooses to be. Mercury does not preflight-tokenize requests, because most supported providers (Anthropic, DeepSeek, Grok, Ollama, etc.) use different tokenizers than OpenAI's `tiktoken`.++## Configuration++Saver state is persisted in `~/.mercury/mercury.yaml` under the `tokens` section:++```yaml+tokens:+ dailyBudget: 1000000+ saverMode: false # true when user runs /saver on+ saverAutoEnabled: true # master switch for auto-engagement+ saverAutoThreshold: 75 # percentage at which auto-engage triggers+ saverTokensSavedLifetime: 0 # lifetime savings counter+```++All fields are optional. Existing installs without saver fields work unchanged — defaults are applied silently on read, and no file is rewritten until you first toggle saver on or it auto-engages.++## Zero-Impact Guarantee When Off++When `saverMode: false` (the default) and saver has never auto-engaged:++- `maxOutputTokens` and `stopWhen` use their original constants byte-for-byte+- The recent-history window is `10` exactly+- The system prompt is identical to a pre-saver install, including the existing `>70%` "Be concise" nudge+- The CLI status bar omits the `⚡SAVER` badge entirely (no layout change)+- `mercury.yaml` and `token-usage.json` are not rewritten+- The provider fallback order is untouched++The only observable difference from a pre-saver install is the addition of `/saver` to the slash-command autocomplete list and the Telegram BotFather command menu.++## When to Use It++Useful situations:++- **You're close to your daily budget** — auto-engagement handles this automatically at 75%+- **You're doing quick lookups or status checks** — manual `/saver on` keeps responses tight+- **You're running an unattended batch of agent tasks** — saver caps response size to avoid runaway output+- **You're on a metered/limited plan** — combine `/saver on` with `/saver routing on` to prefer cheap providers++Less useful situations:++- **Deep debugging or code exploration** — the smaller history window and shorter responses can hurt continuity+- **Long-form writing** — the "be terse" suffix actively fights against generating long content