Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat: implement asynchronous shell command execution with configurable timeouts and add background task management support
Salman Qureshi5aebd41ef096
diff --git a/src/capabilities/git/git-add.ts b/src/capabilities/git/git-add.tsindex 6bf2c1c9..33820047 100644--- a/src/capabilities/git/git-add.ts+++ b/src/capabilities/git/git-add.ts@@ -11,7 +11,7 @@ export function createGitAddTool(getCwd: () => string) {execute: async ({ paths }) => {try {const fileArgs = paths.map(p => `"${p}"`).join(' ');- const result = execSync(`git add ${fileArgs}`, { encoding: 'utf-8', timeout: 10000, cwd: getCwd() });+ const result = execSync(`git add ${fileArgs}`, { encoding: 'utf-8', timeout: 20000, cwd: getCwd() });return `Staged ${paths.length} file(s): ${paths.join(', ')}`;} catch (err: any) {return `Error: ${err.stderr?.trim() || err.message}`;diff --git a/src/capabilities/git/git-commit.ts b/src/capabilities/git/git-commit.tsindex 0365503b..da4d4272 100644--- a/src/capabilities/git/git-commit.ts+++ b/src/capabilities/git/git-commit.ts@@ -20,7 +20,7 @@ export function createGitCommitTool(getCwd: () => string) {writeFileSync(msgFilePath, fullMessage, 'utf-8');const result = execSync(`git commit -F "${msgFilePath}"`, {encoding: 'utf-8',- timeout: 10000,+ timeout: 20000,cwd,});try { unlinkSync(msgFilePath); } catch {}diff --git a/src/capabilities/git/git-diff.ts b/src/capabilities/git/git-diff.tsindex d07a276d..8dab6b02 100644--- a/src/capabilities/git/git-diff.ts+++ b/src/capabilities/git/git-diff.ts@@ -14,7 +14,7 @@ export function createGitDiffTool(getCwd: () => string) {let cmd = 'git diff';if (staged) cmd += ' --cached';if (path) cmd += ` -- "${path}"`;- const result = execSync(cmd, { encoding: 'utf-8', timeout: 15000, cwd: getCwd() });+ const result = execSync(cmd, { encoding: 'utf-8', timeout: 30000, cwd: getCwd() });if (!result.trim()) return 'No differences found.';const truncated = result.length > 15000 ? result.slice(0, 15000) + '\n... (truncated)' : result;return truncated;diff --git a/src/capabilities/git/git-log.ts b/src/capabilities/git/git-log.tsindex 97381446..38f8d5aa 100644--- a/src/capabilities/git/git-log.ts+++ b/src/capabilities/git/git-log.ts@@ -14,7 +14,7 @@ export function createGitLogTool(getCwd: () => string) {const n = count ?? 10;let cmd = `git log --oneline --decorate -${n}`;if (path) cmd += ` -- "${path}"`;- const result = execSync(cmd, { encoding: 'utf-8', timeout: 10000, cwd: getCwd() });+ const result = execSync(cmd, { encoding: 'utf-8', timeout: 20000, cwd: getCwd() });if (!result.trim()) return 'No commits found.';return result.trim();} catch (err: any) {diff --git a/src/capabilities/git/git-push.ts b/src/capabilities/git/git-push.tsindex 209637a1..68533d28 100644--- a/src/capabilities/git/git-push.ts+++ b/src/capabilities/git/git-push.ts@@ -18,7 +18,7 @@ export function createGitPushTool(permissions: PermissionManager, getCwd: () =>}try {- const result = execSync(cmd, { encoding: 'utf-8', timeout: 30000, cwd: getCwd() });+ const result = execSync(cmd, { encoding: 'utf-8', timeout: 60000, cwd: getCwd() });return result.trim() || 'Pushed successfully.';} catch (err: any) {return `Error: ${err.stderr?.trim() || err.message}`;diff --git a/src/capabilities/git/git-status.ts b/src/capabilities/git/git-status.tsindex a8bf0766..4e49de1d 100644--- a/src/capabilities/git/git-status.ts+++ b/src/capabilities/git/git-status.ts@@ -11,7 +11,7 @@ export function createGitStatusTool(getCwd: () => string) {execute: async ({ path }) => {try {const cmd = path ? `git -C "${path}" status --porcelain` : 'git status --porcelain';- const result = execSync(cmd, { encoding: 'utf-8', timeout: 10000, cwd: getCwd() });+ const result = execSync(cmd, { encoding: 'utf-8', timeout: 20000, cwd: getCwd() });if (!result.trim()) return 'Working tree clean — no changes.';return result.trim();} catch (err: any) {diff --git a/src/capabilities/shell/run-command.ts b/src/capabilities/shell/run-command.tsindex 9a410fc2..fcba78a5 100644--- a/src/capabilities/shell/run-command.ts+++ b/src/capabilities/shell/run-command.ts@@ -1,55 +1,140 @@import { tool, zodSchema } from 'ai';import { z } from 'zod';-import { execSync } from 'node:child_process';+import { spawn } from 'node:child_process';import { resolve, isAbsolute } from 'node:path';import { existsSync } from 'node:fs';import { homedir } from 'node:os';import type { PermissionManager } from '../permissions.js';import { logger } from '../../utils/logger.js';+const DEFAULT_TIMEOUT_MS = 120_000;+const MAX_BUFFER = 1024 * 1024;+const SIGTERM_GRACE_MS = 5_000;++interface ExecResult {+ stdout: string;+ stderr: string;+ exitCode: number | null;+ timedOut: boolean;+}++function executeCommand(command: string, cwd: string, timeoutMs: number): Promise<ExecResult> {+ return new Promise((resolve) => {+ let stdout = '';+ let stderr = '';+ let settled = false;+ let timeoutHandle: ReturnType<typeof setTimeout> | undefined;+ let sigkillHandle: ReturnType<typeof setTimeout> | undefined;++ const child = spawn(command, [], {+ cwd,+ shell: true,+ stdio: ['pipe', 'pipe', 'pipe'],+ });++ const finish = (exitCode: number | null, timedOut: boolean) => {+ if (settled) return;+ settled = true;+ if (timeoutHandle) clearTimeout(timeoutHandle);+ if (sigkillHandle) clearTimeout(sigkillHandle);+ resolve({ stdout, stderr, exitCode, timedOut });+ };++ child.stdout.on('data', (chunk: Buffer) => {+ if (stdout.length < MAX_BUFFER) {+ stdout += chunk.toString();+ if (stdout.length > MAX_BUFFER) {+ stdout = stdout.slice(stdout.length - MAX_BUFFER);+ }+ }+ });++ child.stderr.on('data', (chunk: Buffer) => {+ if (stderr.length < MAX_BUFFER) {+ stderr += chunk.toString();+ if (stderr.length > MAX_BUFFER) {+ stderr = stderr.slice(stderr.length - MAX_BUFFER);+ }+ }+ });++ child.on('error', (err) => {+ stderr += `\nProcess error: ${err.message}`;+ finish(null, false);+ });++ child.on('exit', (code) => {+ finish(code, false);+ });++ if (timeoutMs > 0) {+ timeoutHandle = setTimeout(() => {+ if (!settled) {+ child.kill('SIGTERM');+ sigkillHandle = setTimeout(() => {+ if (!settled) {+ child.kill('SIGKILL');+ }+ }, SIGTERM_GRACE_MS);+ finish(null, true);+ }+ }, timeoutMs);+ }+ });+}+export function createRunCommandTool(permissions: PermissionManager, getCwd: () => string, setCwd: (dir: string) => void) {return tool({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 prompt the user for approval before execution.`,+Other commands prompt the user for approval before execution.+The optional timeout parameter sets how long (in seconds) the command can run before being killed (default 120, max 600). For very long builds or test suites, set a higher timeout or use /bg to run the command in the background.`,inputSchema: zodSchema(z.object({command: z.string().describe('The shell command to execute'),+ timeout: z.number().min(10).max(600).default(120).optional().describe('Timeout in seconds (default 120, max 600). Increase for long-running commands like builds or test suites.'),})),- execute: async ({ command }) => {+ execute: async ({ command, timeout }) => {const check = await permissions.checkShellCommand(command);if (!check.allowed) {return `Error: ${check.reason}`;}const cwd = getCwd();+ const timeoutMs = (timeout ?? 120) * 1000;try {- logger.info({ cmd: command, cwd }, 'Executing shell command');- const result = execSync(command, {- cwd,- timeout: 30000,- maxBuffer: 1024 * 1024,- encoding: 'utf-8',- stdio: ['pipe', 'pipe', 'pipe'],- });+ logger.info({ cmd: command, cwd, timeoutMs }, 'Executing shell command');+ const result = await executeCommand(command, cwd, timeoutMs);- const trimmedOutput = result?.trim() || '(no output)';-- detectCd(command, cwd, setCwd);+ if (result.stdout || result.stderr) {+ detectCd(command, cwd, setCwd);+ }- return trimmedOutput;- } catch (err: any) {- const stderr = err.stderr?.trim();- const stdout = err.stdout?.trim();+ if (result.timedOut) {+ const partial = result.stdout?.trim();+ let msg = `⏱ Command timed out after ${timeoutMs / 1000}s.`;+ if (partial) {+ const lines = partial.split('\n');+ const preview = lines.length > 30 ? lines.slice(-30).join('\n') : partial;+ msg += `\nPartial output:\n${preview}`;+ }+ msg += '\n\nTo run long commands in the background, use /bg <command>.';+ return msg;+ }- if (stdout || stderr) {- detectCd(command, cwd, setCwd);+ const trimmedOutput = result.stdout?.trim() || '(no output)';+ if (result.exitCode !== 0 && result.exitCode !== null) {+ let msg = `Command exited with code ${result.exitCode}`;+ if (trimmedOutput && trimmedOutput !== '(no output)') msg += `\nOutput: ${trimmedOutput}`;+ if (result.stderr?.trim()) msg += `\nError: ${result.stderr.trim()}`;+ return msg;}- let msg = `Command exited with code ${err.status || 'unknown'}`;- if (stdout) msg += `\nOutput: ${stdout}`;- if (stderr) msg += `\nError: ${stderr}`;+ detectCd(command, cwd, setCwd);+ return trimmedOutput;+ } catch (err: any) {+ let msg = `Command failed: ${err.message || String(err)}`;return msg;}},diff --git a/src/capabilities/web/fetch-url.ts b/src/capabilities/web/fetch-url.tsindex 24ae85da..40a333ea 100644--- a/src/capabilities/web/fetch-url.ts+++ b/src/capabilities/web/fetch-url.ts@@ -53,7 +53,7 @@ export function createFetchUrlTool() {try {const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), 15000);+ const timeout = setTimeout(() => controller.abort(), 30000);const resp = await fetch(url, {signal: controller.signal,@@ -96,7 +96,7 @@ export function createFetchUrlTool() {: body;} catch (err: any) {if (err.name === 'AbortError') {- return `Request to ${url} timed out after 15 seconds.`;+ return `Request to ${url} timed out after 30 seconds.`;}return `Error fetching ${url}: ${err.message}`;}diff --git a/src/channels/cli.ts b/src/channels/cli.tsindex a861375b..54516c1d 100644--- a/src/channels/cli.ts+++ b/src/channels/cli.ts@@ -7,7 +7,7 @@ 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, ToolStep, PermissionPromptState, SidebarSection, SkillInfo, SubAgentInfo, ProviderInfo, TokenInfo, AppMode, WorkspaceState, WorkspaceTreeNode, WorkspaceGitFile } from '../ui/types.js';+import type { ChatMessage, ToolStep, PermissionPromptState, SidebarSection, SkillInfo, SubAgentInfo, ProviderInfo, TokenInfo, AppMode, WorkspaceState, WorkspaceTreeNode, WorkspaceGitFile, BackgroundTaskInfo } from '../ui/types.js';import { TuiApp } from '../ui/App.js';export interface TuiState {@@ -28,6 +28,7 @@ export interface TuiState {projectContext: string | null;permissionMode: PermissionMode;workspace: WorkspaceState | null;+ backgroundTasks: BackgroundTaskInfo[];}const defaultState: TuiState = {@@ -48,6 +49,7 @@ const defaultState: TuiState = {projectContext: null,permissionMode: 'ask-me',workspace: null,+ backgroundTasks: [],};export class CLIChannel extends BaseChannel {@@ -438,6 +440,10 @@ export class CLIChannel extends BaseChannel {this.update({ subAgents: agents });}+ updateBackgroundTasks(tasks: BackgroundTaskInfo[]): void {+ this.update({ backgroundTasks: tasks });+ }+setSidebarSections(sections: SidebarSection[]): void {this.update({ sidebarSections: sections });}diff --git a/src/core/agent.ts b/src/core/agent.tsindex 56e1c333..8bec71ed 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -14,6 +14,7 @@ import { DeepSeekProvider } from '../providers/deepseek.js';import { Lifecycle } from './lifecycle.js';import { Scheduler } from './scheduler.js';import { ProgrammingMode } from './programming-mode.js';+import { BackgroundTaskManager } from './background-tasks.js';import { logger } from '../utils/logger.js';import { CLIChannel } from '../channels/cli.js';import { TelegramChannel } from '../channels/telegram.js';@@ -257,6 +258,7 @@ export class Agent {private supervisor?: import('../core/supervisor.js').SubAgentSupervisor;readonly programmingMode: ProgrammingMode;private spotifyClient?: SpotifyClient;+ readonly backgroundTasks: BackgroundTaskManager;constructor(private config: MercuryConfig,@@ -276,6 +278,11 @@ export class Agent {this.capabilities = capabilities;this.telegramStreaming = config.channels.telegram.streaming ?? true;this.programmingMode = new ProgrammingMode();+ this.backgroundTasks = new BackgroundTaskManager();++ this.backgroundTasks.onGlobalComplete((task) => {+ this.notifyBackgroundTaskComplete(task);+ });this.scheduler.setOnScheduledTask(async (manifest) => this.handleScheduledTask(manifest));@@ -354,8 +361,13 @@ export class Agent {return;}+ if (trimmed.startsWith('/bg')) {+ await this.handleBgCommand(trimmed, msg, channel);+ return;+ }+if (trimmed === '/help') {- await channel.send('Agent is busy. Available: /agents, /halt, /stop, /spotify, /code, /memory', msg.channelId);+ await channel.send('Agent is busy. Available: /agents, /halt, /stop, /spotify, /code, /memory, /bg', msg.channelId);return;}@@ -427,6 +439,161 @@ export class Agent {await channel.send('Agent is busy. Programming mode changes will be available after current task completes.', msg.channelId);}+ private async handleBgCommand(trimmed: string, msg: ChannelMessage, channel: any): Promise<void> {+ const parts = trimmed.split(/\s+/);+ const sub = parts.length > 1 ? parts[1] : '';+ const args = parts.slice(1).join(' ');++ if (sub === 'list' || sub === '' || sub === 'ls') {+ const tasks = this.backgroundTasks.getAllSummaries();+ if (tasks.length === 0) {+ await channel.send('No background tasks.', msg.channelId);+ return;+ }+ const lines = tasks.map((t) => {+ const icon = t.status === 'running' ? '⏳' : t.status === 'completed' ? '✅' : t.status === 'failed' ? '❌' : t.status === 'timed_out' ? '⏱' : '⛔';+ const label = t.command || t.task || t.id;+ const elapsed = t.runningMs ? ` (${Math.round(t.runningMs / 1000)}s)` : t.completedAt ? ` (${((t.completedAt - t.startedAt) / 1000).toFixed(1)}s)` : '';+ const short = label.length > 60 ? label.slice(0, 57) + '...' : label;+ return `${icon} ${t.id}: ${short}${elapsed} — ${t.status}`;+ });+ await channel.send(`**Background Tasks:**\n${lines.join('\n')}\n\nUse /bg <id> for details, /bg cancel <id> to cancel, /bg clear to prune completed tasks.`, msg.channelId);+ return;+ }++ if (sub === 'clear') {+ const cleared = this.backgroundTasks.clearCompleted();+ await channel.send(`Cleared ${cleared} completed task(s).`, msg.channelId);+ this.syncBgTasksToTui();+ return;+ }++ if (sub === 'cancel') {+ const taskId = parts[2];+ if (!taskId) {+ await channel.send('Usage: /bg cancel <id>', msg.channelId);+ return;+ }+ const cancelled = this.backgroundTasks.cancel(taskId);+ if (cancelled) {+ await channel.send(`⛔ Cancelled background task ${taskId}.`, msg.channelId);+ } else {+ await channel.send(`Task ${taskId} not found or not running.`, msg.channelId);+ }+ this.syncBgTasksToTui();+ return;+ }++ const specificTask = this.backgroundTasks.getSummary(sub);+ if (specificTask) {+ const task = this.backgroundTasks.get(sub)!;+ const label = task.command || task.task || task.id;+ const elapsed = task.status === 'running'+ ? `Running for ${Math.round((Date.now() - task.startedAt) / 1000)}s`+ : task.completedAt+ ? `Completed in ${((task.completedAt - task.startedAt) / 1000).toFixed(1)}s`+ : task.status;+ const output = (task.stdout + '\n' + task.stderr).trim();+ const preview = output.length > 2000 ? output.slice(-2000) : output;+ await channel.send(`**${specificTask.id}**: ${label}\nStatus: ${elapsed}\nExit code: ${task.exitCode ?? 'N/A'}\n\n${preview || '(no output)'}`, msg.channelId);+ return;+ }++ const colonIdx = trimmed.indexOf(':');+ if (sub.startsWith('cancel')) {+ const taskId2 = parts[2];+ if (!taskId2) {+ await channel.send('Usage: /bg cancel <id>', msg.channelId);+ return;+ }+ const cancelled = this.backgroundTasks.cancel(taskId2);+ if (cancelled) {+ await channel.send(`⛔ Cancelled background task ${taskId2}.`, msg.channelId);+ } else {+ await channel.send(`Task ${taskId2} not found or not running.`, msg.channelId);+ }+ this.syncBgTasksToTui();+ return;+ }++ if (colonIdx !== -1 && trimmed[colonIdx + 1] === ' ') {+ const taskDescription = trimmed.slice(colonIdx + 1).trim();+ if (!taskDescription) {+ await channel.send('Usage: /bg: <natural language task> or /bg <shell command>', msg.channelId);+ return;+ }+ if (!this.supervisor) {+ await channel.send('Sub-agents are not available. Use /bg <command> for shell commands.', msg.channelId);+ return;+ }+ const agentId = await this.supervisor.spawn({+ task: taskDescription,+ sourceChannelId: msg.channelId,+ sourceChannelType: msg.channelType as any,+ });+ const bgId = this.backgroundTasks.spawnAgent(taskDescription, this.capabilities.getCwd(), agentId);+ this.backgroundTasks.registerComplete(bgId, (task) => {+ if (task.status === 'running') return;+ });+ await channel.send(`📋 Background agent ${bgId} started: "${taskDescription.slice(0, 50)}${taskDescription.length > 50 ? '...' : ''}"`, msg.channelId);+ this.syncBgTasksToTui();+ return;+ }++ const command = args || '';+ if (!command) {+ await channel.send('Usage:\n• /bg <command> — run a shell command in the background\n• /bg: <task> — delegate an LLM task to the background\n• /bg list — show all background tasks\n• /bg <id> — show task details\n• /bg cancel <id> — cancel a running task\n• /bg clear — prune completed tasks', msg.channelId);+ return;+ }++ const cwd = this.capabilities.getCwd();+ const bgId = this.backgroundTasks.spawnShell(command, cwd);+ await channel.send(`📋 Background task ${bgId} started: "${command.slice(0, 50)}${command.length > 50 ? '...' : ''}"`, msg.channelId);+ this.syncBgTasksToTui();+ }++ private syncBgTasksToTui(): void {+ const cliChannel = this.channels.get('cli');+ if (cliChannel && cliChannel instanceof CLIChannel) {+ (cliChannel as CLIChannel).updateBackgroundTasks(this.backgroundTasks.getAllSummaries());+ }+ }++ private notifyBackgroundTaskComplete(task: import('./background-tasks.js').BackgroundTask): void {+ const label = task.command || task.task || task.id;+ const duration = task.completedAt ? ` in ${((task.completedAt - task.startedAt) / 1000).toFixed(1)}s` : '';+ let message: string;++ if (task.status === 'completed') {+ message = `✅ Background task ${task.id} completed${duration}: "${label}"`;+ } else if (task.status === 'failed') {+ message = `❌ Background task ${task.id} failed${duration}: "${label}" (exit code ${task.exitCode ?? 'unknown'})`;+ } else if (task.status === 'timed_out') {+ message = `⏱ Background task ${task.id} timed out: "${label}"`;+ } else if (task.status === 'cancelled') {+ message = `⛔ Background task ${task.id} cancelled: "${label}"`;+ } else {+ message = `Background task ${task.id}: ${task.status} — "${label}"`;+ }++ const output = (task.stdout + '\n' + task.stderr).trim();+ if (output) {+ const preview = output.length > 500 ? '\n' + output.slice(-500) : '\n' + output;+ message += preview;+ }++ const cliCh = this.channels.get('cli');+ if (cliCh) {+ (cliCh as CLIChannel).send(message).catch(() => {});+ }+ const tgCh = this.channels.get('telegram');+ if (tgCh) {+ tgCh.send(message).catch(() => {});+ }++ this.syncBgTasksToTui();+ }+private async processQueue(): Promise<void> {if (this.processing) return;if (this.messageQueue.length === 0) return;@@ -1459,6 +1626,12 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub userreturn true;}+ if (cmd.startsWith('/bg')) {+ const args = trimmed.slice('/bg'.length).trim();+ await this.handleBgCommand(args, { content: trimmed, channelId, channelType: channelType as any, id: Date.now().toString(36), senderId: 'user', timestamp: Date.now() }, channel);+ return true;+ }+if (cmd === '/exit' || cmd === '/quit') {await channel.send('Goodbye! Shutting down Mercury...', channelId);this.shutdown();diff --git a/src/core/background-tasks.ts b/src/core/background-tasks.tsnew file mode 100644index 00000000..8b02985e--- /dev/null+++ b/src/core/background-tasks.ts@@ -0,0 +1,364 @@+import { spawn, type ChildProcess } from 'node:child_process';+import { logger } from '../utils/logger.js';++export type BgTaskType = 'shell' | 'agent';+export type BgTaskStatus = 'running' | 'completed' | 'failed' | 'timed_out' | 'cancelled';++export interface BackgroundTask {+ id: string;+ type: BgTaskType;+ command?: string;+ task?: string;+ cwd: string;+ status: BgTaskStatus;+ pid?: number;+ agentId?: string;+ startedAt: number;+ completedAt?: number;+ exitCode: number | null;+ stdout: string;+ stderr: string;+ timeoutMs: number;+}++export interface BackgroundTaskSummary {+ id: string;+ type: BgTaskType;+ command?: string;+ task?: string;+ status: BgTaskStatus;+ startedAt: number;+ completedAt?: number;+ exitCode: number | null;+ outputPreview: string;+ runningMs?: number;+}++const MAX_OUTPUT = 1024 * 1024;+const MAX_TASKS = 20;+const PRUNE_AGE_MS = 60 * 60 * 1000;+const SIGTERM_GRACE_MS = 3000;+const MAX_PREVIEW = 200;+const DEFAULT_SHELL_TIMEOUT_MS = 0;++let taskCounter = 0;++function nextId(): string {+ return `bg-${++taskCounter}`;+}++function tailTruncate(str: string, maxLen: number): string {+ if (str.length <= maxLen) return str;+ return str.slice(str.length - maxLen);+}++export type TaskCompleteCallback = (task: BackgroundTask) => void;++export class BackgroundTaskManager {+ private tasks: Map<string, BackgroundTask> = new Map();+ private processes: Map<string, ChildProcess> = new Map();+ private timeouts: Map<string, ReturnType<typeof setTimeout>> = new Map();+ private sigkillTimeouts: Map<string, ReturnType<typeof setTimeout>> = new Map();+ private onCompleteCallbacks: Map<string, TaskCompleteCallback> = new Map();+ private globalOnComplete?: TaskCompleteCallback;+ private pruneInterval: ReturnType<typeof setInterval> | null = null;++ constructor() {+ this.pruneInterval = setInterval(() => this.prune(), 5 * 60 * 1000);+ }++ destroy(): void {+ if (this.pruneInterval) {+ clearInterval(this.pruneInterval);+ this.pruneInterval = null;+ }+ for (const [id, child] of this.processes) {+ try { child.kill('SIGTERM'); } catch {}+ }+ for (const [, t] of this.timeouts) {+ clearTimeout(t);+ }+ for (const [, t] of this.sigkillTimeouts) {+ clearTimeout(t);+ }+ }++ onGlobalComplete(cb: TaskCompleteCallback): void {+ this.globalOnComplete = cb;+ }++ spawnShell(command: string, cwd: string, timeoutMs: number = DEFAULT_SHELL_TIMEOUT_MS): string {+ this.enforceTaskLimit();++ const id = nextId();+ const task: BackgroundTask = {+ id,+ type: 'shell',+ command,+ cwd,+ status: 'running',+ pid: undefined,+ startedAt: Date.now(),+ exitCode: null,+ stdout: '',+ stderr: '',+ timeoutMs,+ };+ this.tasks.set(id, task);++ try {+ const child = spawn(command, [], {+ cwd,+ shell: true,+ stdio: ['pipe', 'pipe', 'pipe'],+ });++ task.pid = child.pid ?? undefined;+ this.processes.set(id, child);++ child.stdout?.on('data', (chunk: Buffer) => {+ task.stdout += chunk.toString();+ if (task.stdout.length > MAX_OUTPUT) {+ task.stdout = tailTruncate(task.stdout, MAX_OUTPUT);+ }+ });++ child.stderr?.on('data', (chunk: Buffer) => {+ task.stderr += chunk.toString();+ if (task.stderr.length > MAX_OUTPUT) {+ task.stderr = tailTruncate(task.stderr, MAX_OUTPUT);+ }+ });++ child.on('error', (err) => {+ task.stderr += `\nProcess error: ${err.message}`;+ this.completeTask(id, null, 'failed');+ });++ child.on('exit', (code) => {+ this.completeTask(id, code, code === 0 ? 'completed' : 'failed');+ });++ if (timeoutMs > 0) {+ const timeout = setTimeout(() => {+ this.killTask(id, 'SIGTERM');+ const sigkillTimeout = setTimeout(() => {+ this.killTask(id, 'SIGKILL');+ }, SIGTERM_GRACE_MS);+ this.sigkillTimeouts.set(id, sigkillTimeout);++ if (task.status === 'running') {+ task.status = 'timed_out';+ this.completeTask(id, null, 'timed_out');+ }+ }, timeoutMs);+ this.timeouts.set(id, timeout);+ }++ logger.info({ taskId: id, command, cwd }, 'Background shell task started');+ } catch (err: any) {+ task.status = 'failed';+ task.stderr = `Failed to spawn: ${err.message}`;+ task.completedAt = Date.now();+ task.exitCode = null;+ }++ return id;+ }++ spawnAgent(taskDescription: string, cwd: string, agentId: string): string {+ this.enforceTaskLimit();++ const id = nextId();+ const task: BackgroundTask = {+ id,+ type: 'agent',+ task: taskDescription,+ cwd,+ status: 'running',+ agentId,+ startedAt: Date.now(),+ exitCode: null,+ stdout: '',+ stderr: '',+ timeoutMs: 0,+ };+ this.tasks.set(id, task);+ logger.info({ taskId: id, agentId, task: taskDescription }, 'Background agent task started');+ return id;+ }++ updateAgentProgress(bgTaskId: string, progress: string): void {+ const task = this.tasks.get(bgTaskId);+ if (!task || task.type !== 'agent') return;+ task.stdout += progress + '\n';+ if (task.stdout.length > MAX_OUTPUT) {+ task.stdout = tailTruncate(task.stdout, MAX_OUTPUT);+ }+ }++ completeAgentTask(bgTaskId: string, exitCode: number | null, status: BgTaskStatus, output?: string): void {+ const task = this.tasks.get(bgTaskId);+ if (!task) return;+ if (output) {+ task.stdout = output;+ }+ this.completeTask(bgTaskId, exitCode, status);+ }++ cancel(taskId: string): boolean {+ const task = this.tasks.get(taskId);+ if (!task) return false;+ if (task.status !== 'running') return false;++ if (task.type === 'shell') {+ this.killTask(taskId, 'SIGTERM');+ const sigkill = setTimeout(() => {+ this.killTask(taskId, 'SIGKILL');+ }, SIGTERM_GRACE_MS);+ this.sigkillTimeouts.set(taskId, sigkill);+ }++ task.status = 'cancelled';+ task.completedAt = Date.now();+ task.exitCode = null;+ this.clearTimeouts(taskId);+ this.notifyComplete(task);+ logger.info({ taskId }, 'Background task cancelled');+ return true;+ }++ get(taskId: string): BackgroundTask | undefined {+ return this.tasks.get(taskId);+ }++ getSummary(taskId: string): BackgroundTaskSummary | undefined {+ const task = this.tasks.get(taskId);+ if (!task) return undefined;+ return this.toSummary(task);+ }++ getAll(): BackgroundTask[] {+ return [...this.tasks.values()];+ }++ getAllSummaries(): BackgroundTaskSummary[] {+ return [...this.tasks.values()].map(this.toSummary);+ }++ getRunning(): BackgroundTask[] {+ return [...this.tasks.values()].filter(t => t.status === 'running');+ }++ getRunningSummaries(): BackgroundTaskSummary[] {+ return this.getRunning().map(this.toSummary);+ }++ registerComplete(taskId: string, cb: TaskCompleteCallback): void {+ this.onCompleteCallbacks.set(taskId, cb);+ }++ prune(): number {+ const now = Date.now();+ let pruned = 0;+ for (const [id, task] of this.tasks) {+ if (task.status === 'running') continue;+ if (task.completedAt && (now - task.completedAt) > PRUNE_AGE_MS) {+ this.tasks.delete(id);+ pruned++;+ }+ }+ if (pruned > 0) {+ logger.info({ pruned }, 'Pruned completed background tasks');+ }+ return pruned;+ }++ clearCompleted(): number {+ let cleared = 0;+ for (const [id, task] of this.tasks) {+ if (task.status !== 'running') {+ this.tasks.delete(id);+ cleared++;+ }+ }+ return cleared;+ }++ getByAgentId(agentId: string): BackgroundTask | undefined {+ for (const task of this.tasks.values()) {+ if (task.agentId === agentId) return task;+ }+ return undefined;+ }++ private completeTask(id: string, exitCode: number | null, status: BgTaskStatus): void {+ const task = this.tasks.get(id);+ if (!task) return;+ if (task.status !== 'running' && task.status !== 'timed_out') return;++ task.exitCode = exitCode;+ task.status = status;+ task.completedAt = Date.now();+ this.clearTimeouts(id);+ this.processes.delete(id);++ logger.info({ taskId: id, status, exitCode }, 'Background task completed');+ this.notifyComplete(task);+ }++ private notifyComplete(task: BackgroundTask): void {+ const cb = this.onCompleteCallbacks.get(task.id);+ if (cb) {+ try { cb(task); } catch {}+ this.onCompleteCallbacks.delete(task.id);+ }+ if (this.globalOnComplete) {+ try { this.globalOnComplete(task); } catch {}+ }+ }++ private killTask(id: string, signal: NodeJS.Signals): void {+ const child = this.processes.get(id);+ if (child) {+ try { child.kill(signal); } catch {}+ }+ }++ private clearTimeouts(id: string): void {+ const t = this.timeouts.get(id);+ if (t) { clearTimeout(t); this.timeouts.delete(id); }+ const s = this.sigkillTimeouts.get(id);+ if (s) { clearTimeout(s); this.sigkillTimeouts.delete(id); }+ }++ private enforceTaskLimit(): void {+ const completed = [...this.tasks.values()]+ .filter(t => t.status !== 'running')+ .sort((a, b) => (a.completedAt ?? 0) - (b.completedAt ?? 0));++ while (this.tasks.size >= MAX_TASKS && completed.length > 0) {+ const oldest = completed.shift();+ if (oldest) {+ this.tasks.delete(oldest.id);+ }+ }+ }++ private toSummary(task: BackgroundTask): BackgroundTaskSummary {+ const combined = task.stdout + '\n' + task.stderr;+ const preview = combined.trim().slice(-MAX_PREVIEW);+ return {+ id: task.id,+ type: task.type,+ command: task.command,+ task: task.task,+ status: task.status,+ startedAt: task.startedAt,+ completedAt: task.completedAt,+ exitCode: task.exitCode,+ outputPreview: preview,+ runningMs: task.status === 'running' ? Date.now() - task.startedAt : undefined,+ };+ }+}\ No newline at end of filediff --git a/src/ui/App.tsx b/src/ui/App.tsxindex ad1d0efd..44a30044 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -1,7 +1,7 @@import React from 'react';import { Box, Text, useApp, useInput } from 'ink';import type { TuiState } from '../channels/cli.js';-import type { AppMode, ChatMessage, ToolStep, SubAgentInfo, PermissionPromptState, SidebarSection } from './types.js';+import type { AppMode, ChatMessage, ToolStep, SubAgentInfo, PermissionPromptState, SidebarSection, BackgroundTaskInfo } from './types.js';import type { PermissionMode } from '../channels/base.js';import type { ProgrammingModeState } from '../core/programming-mode.js';import { renderMarkdown } from '../utils/markdown.js';@@ -96,6 +96,10 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCli'/permissions','/memory','/agents',+ '/bg',+ '/bg list',+ '/bg cancel ',+ '/bg clear','/view','/view balanced','/view detailed',@@ -334,11 +338,16 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCliif (state.mode === 'splash') return;- if ((ch === 'v' || ch === 'V') && !state.permissionPrompt) {+ if ((ch === 'v' || ch === 'V') && !state.permissionPrompt && input.length === 0) {onInput('/view toggle');return;}+ if (key.ctrl && (ch === 'b' || ch === 'B') && !state.permissionPrompt) {+ onInput('/bg list');+ return;+ }+if (key.escape) {if (state.mode === 'coding') {onInput('/chat');@@ -463,11 +472,12 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCli);}- const showInput = !state.permissionPrompt && !state.isThinking && (state.mode === 'chat' || state.mode === 'coding' || state.mode === 'workspace');+ const showInput = !state.permissionPrompt && (state.mode === 'chat' || state.mode === 'coding' || state.mode === 'workspace');return (<Box flexDirection="column" flexGrow={1}><StatusBarView state={state} />+ {state.backgroundTasks.length > 0 && <BackgroundBarView tasks={state.backgroundTasks} />}{state.mode === 'spotify' ? <SpotifyBody activeIdx={spotifyIdx} nowPlaying={spotifyNow} /> : null}{state.mode === 'menu' ? <MenuBody menuIdx={menuIdx} /> : null}{state.mode === 'coding' ? <CodingBody state={state} /> : null}@@ -493,6 +503,39 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCli);}+function BackgroundBarView({ tasks }: { tasks: BackgroundTaskInfo[] }) {+ if (tasks.length === 0) return null;++ const statusIcons: Record<string, string> = {+ running: '⏳',+ completed: '✅',+ failed: '❌',+ timed_out: '⏱',+ cancelled: '⛔',+ };++ const visible = tasks.slice(0, 3);+ const more = tasks.length > 3 ? ` +${tasks.length - 3} more` : '';++ return (+ <Box paddingX={1} paddingBottom={0}>+ <Text color="gray">{'─'.repeat(50)}</Text>+ <Box flexDirection="column" width="100%">+ <Box>+ <Text dimColor>⏥ Background:</Text>+ <Text> {visible.map((t) => {+ const icon = statusIcons[t.status] || '·';+ const label = t.command || t.task || t.id;+ const short = label.length > 25 ? label.slice(0, 22) + '...' : label;+ const elapsed = t.runningMs ? ` (${Math.round(t.runningMs / 1000)}s)` : '';+ return `${icon} ${t.id}: ${short}${elapsed}`;+ }).join(' · ')}{more}</Text>+ </Box>+ </Box>+ </Box>+ );+}+function StatusBarView({ state }: { state: TuiState }) {const modeColor = state.programmingMode === 'execute' ? 'green' : state.programmingMode === 'plan' ? 'yellow' : 'gray';const modeLabel = state.programmingMode === 'off' ? '' : ` ${state.programmingMode.toUpperCase()}`;diff --git a/src/ui/types.ts b/src/ui/types.tsindex 0d37d84b..6d178fb4 100644--- a/src/ui/types.ts+++ b/src/ui/types.ts@@ -108,6 +108,22 @@ export interface MercuryAppState {workspace: WorkspaceState | null;}+export type BgTaskType = 'shell' | 'agent';+export type BgTaskStatus = 'running' | 'completed' | 'failed' | 'timed_out' | 'cancelled';++export interface BackgroundTaskInfo {+ id: string;+ type: BgTaskType;+ command?: string;+ task?: string;+ status: BgTaskStatus;+ startedAt: number;+ completedAt?: number;+ exitCode: number | null;+ outputPreview: string;+ runningMs?: number;+}+export interface PermissionPromptState {type: 'mode' | 'ask' | 'continue';message: string;