Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(tools): run_command pulses progress and honours abort
Salman Qureshi57aa117d79a5
diff --git a/src/capabilities/shell/run-command.test.ts b/src/capabilities/shell/run-command.test.tsnew file mode 100644index 00000000..9fcebe92--- /dev/null+++ b/src/capabilities/shell/run-command.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from 'vitest';+import { executeCommand } from './run-command.js';++// Portable long-running child: Node itself, printing a line every 200 ms.+const TICKER = `${JSON.stringify(process.execPath)} -e "let n=0;setInterval(()=>{console.log('tick',++n);},200)"`;+const QUIET = `${JSON.stringify(process.execPath)} -e "setTimeout(()=>{},5000)"`;++describe('run_command executor (ROADMAP P1.8)', () => {+ it('pulses on output so a streaming build counts as progress', async () => {+ let pulses = 0;+ const controller = new AbortController();+ const run = executeCommand(TICKER, process.cwd(), 10_000, { signal: controller.signal, onActivity: () => { pulses++; } });+ await new Promise((r) => setTimeout(r, 900));+ controller.abort();+ const result = await run;+ expect(pulses).toBeGreaterThanOrEqual(3);+ expect(result.aborted).toBe(true);+ expect(result.timedOut).toBe(false);+ expect(result.stdout).toContain('tick');+ });++ it('terminates the child promptly when the agent loop aborts', async () => {+ const controller = new AbortController();+ const started = Date.now();+ const run = executeCommand(QUIET, process.cwd(), 30_000, { signal: controller.signal });+ setTimeout(() => controller.abort(), 150);+ const result = await run;+ expect(result.aborted).toBe(true);+ expect(Date.now() - started).toBeLessThan(5_000);+ });++ it('returns aborted immediately when the signal is already aborted', async () => {+ const controller = new AbortController();+ controller.abort();+ const result = await executeCommand(QUIET, process.cwd(), 30_000, { signal: controller.signal });+ expect(result.aborted).toBe(true);+ });++ it('still reports a timeout as timed out, not aborted', async () => {+ const result = await executeCommand(QUIET, process.cwd(), 300);+ expect(result.timedOut).toBe(true);+ expect(result.aborted).toBe(false);+ });++ it('reports exit codes for normal completion', async () => {+ const ok = await executeCommand(`${JSON.stringify(process.execPath)} -e "console.log('hi')"`, process.cwd(), 5_000);+ expect(ok.exitCode).toBe(0);+ expect(ok.stdout.trim()).toBe('hi');+ const bad = await executeCommand(`${JSON.stringify(process.execPath)} -e "process.exit(3)"`, process.cwd(), 5_000);+ expect(bad.exitCode).toBe(3);+ });+});diff --git a/src/capabilities/shell/run-command.ts b/src/capabilities/shell/run-command.tsindex a0ecead1..08ee5b98 100644--- a/src/capabilities/shell/run-command.ts+++ b/src/capabilities/shell/run-command.ts@@ -7,6 +7,7 @@ import { homedir } from 'node:os';import type { PermissionManager } from '../permissions.js';import { redactSecrets } from '../../utils/redact.js';import { logger } from '../../utils/logger.js';+import { pulseProgress, TOOL_PULSE_INTERVAL_MS } from '../../core/progress-pulse.js';const DEFAULT_TIMEOUT_MS = 120_000;const MAX_BUFFER = 1024 * 1024;@@ -19,15 +20,26 @@ interface ExecResult {stderr: string;exitCode: number | null;timedOut: boolean;+ /** The agent loop was aborted (user interrupt, watchdog) while the command ran. */+ aborted: boolean;}-function executeCommand(command: string, cwd: string, timeoutMs: number): Promise<ExecResult> {+interface ExecOptions {+ /** Abort from the agent loop; the child is terminated when it fires. */+ signal?: AbortSignal;+ /** Called on output and periodically while the child is alive. */+ onActivity?: () => void;+}++export function executeCommand(command: string, cwd: string, timeoutMs: number, options: ExecOptions = {}): 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;+ let pulseHandle: ReturnType<typeof setInterval> | undefined;+ const { signal, onActivity } = options;const child = spawn(command, [], {cwd,@@ -35,15 +47,32 @@ function executeCommand(command: string, cwd: string, timeoutMs: number): Promisstdio: ['pipe', 'pipe', 'pipe'],});- const finish = (exitCode: number | null, timedOut: boolean) => {+ const onAbort = () => terminate('abort');++ const finish = (exitCode: number | null, timedOut: boolean, aborted = false) => {if (settled) return;settled = true;if (timeoutHandle) clearTimeout(timeoutHandle);if (sigkillHandle) clearTimeout(sigkillHandle);- resolve({ stdout, stderr, exitCode, timedOut });+ if (pulseHandle) clearInterval(pulseHandle);+ signal?.removeEventListener('abort', onAbort);+ resolve({ stdout, stderr, exitCode, timedOut, aborted });+ };++ // SIGTERM, then SIGKILL after a grace period. Used for both the tool's+ // own timeout and an abort from the agent loop — previously an aborted+ // turn left the child running to completion.+ const terminate = (reason: 'timeout' | 'abort') => {+ if (settled) return;+ child.kill('SIGTERM');+ sigkillHandle = setTimeout(() => {+ if (!child.killed || child.exitCode === null) child.kill('SIGKILL');+ }, SIGTERM_GRACE_MS);+ finish(null, reason === 'timeout', reason === 'abort');};child.stdout.on('data', (chunk: Buffer) => {+ onActivity?.();if (stdout.length < MAX_BUFFER) {stdout += chunk.toString();if (stdout.length > MAX_BUFFER) {@@ -53,6 +82,7 @@ function executeCommand(command: string, cwd: string, timeoutMs: number): Promis});child.stderr.on('data', (chunk: Buffer) => {+ onActivity?.();if (stderr.length < MAX_BUFFER) {stderr += chunk.toString();if (stderr.length > MAX_BUFFER) {@@ -70,18 +100,23 @@ function executeCommand(command: string, cwd: string, timeoutMs: number): Promisfinish(code, false);});+ if (signal) {+ if (signal.aborted) {+ onAbort();+ return;+ }+ signal.addEventListener('abort', onAbort, { once: true });+ }++ // A quiet build (no output for minutes) is still progress as long as the+ // child is alive and inside its own timeout. Pulse so the stall watchdog+ // does not abort the turn underneath it.+ if (onActivity) {+ pulseHandle = setInterval(onActivity, TOOL_PULSE_INTERVAL_MS);+ }+if (timeoutMs > 0) {- timeoutHandle = setTimeout(() => {- if (!settled) {- child.kill('SIGTERM');- sigkillHandle = setTimeout(() => {- if (!settled) {- child.kill('SIGKILL');- }- }, SIGTERM_GRACE_MS);- finish(null, true);- }- }, timeoutMs);+ timeoutHandle = setTimeout(() => terminate('timeout'), timeoutMs);}});}@@ -97,7 +132,7 @@ The optional timeout parameter sets how long (in seconds) the command can run becommand: 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, timeout }) => {+ execute: async ({ command, timeout }, toolOptions?: { abortSignal?: AbortSignal }) => {const check = await permissions.checkShellCommand(command);if (!check.allowed) {return `Error: ${check.reason}`;@@ -108,12 +143,22 @@ The optional timeout parameter sets how long (in seconds) the command can run betry {logger.info({ cmd: command, cwd, timeoutMs }, 'Executing shell command');- const result = await executeCommand(command, cwd, timeoutMs);+ const result = await executeCommand(command, cwd, timeoutMs, {+ signal: toolOptions?.abortSignal,+ onActivity: pulseProgress,+ });if (result.stdout || result.stderr) {detectCd(command, cwd, setCwd);}+ if (result.aborted) {+ const partial = result.stdout?.trim();+ let msg = '⛔ Command stopped: the turn was interrupted before it finished.';+ if (partial) msg += `\nPartial output:\n${redactSecrets(partial.split('\n').slice(-30).join('\n'))}`;+ return msg;+ }+if (result.timedOut) {const partial = result.stdout?.trim();let msg = `⏱ Command timed out after ${timeoutMs / 1000}s.`;diff --git a/src/core/agent.ts b/src/core/agent.tsindex 968f4462..58632666 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -89,6 +89,7 @@ import { HISTORY_TOKEN_BUDGET, HISTORY_TOKEN_BUDGET_SAVER, TOOL_TRACE_KIND, seleimport { buildStatusVerbPrompt, parseStatusVerbs, shouldRefreshStatusVerbs } from './status-verbs.js';import { verbPoolFor } from '../ui/status-word.js';import { StallWatchdog } from './stall-watchdog.js';+import { setProgressPulse } from './progress-pulse.js';import { buildFileChangePreview } from '../utils/file-preview.js';import { whatsNewText } from '../utils/whats-new.js';@@ -552,6 +553,7 @@ export class Agent {this.lifecycle = new Lifecycle();this.scheduler = scheduler;this.capabilities = capabilities;+ this.installProgressPulse();this.telegramStreaming = config.channels.telegram.streaming ?? true;this.programmingMode = new ProgrammingMode();this.researchMode = new ResearchMode();@@ -2207,6 +2209,15 @@ export class Agent {}}+ /**+ * Long-running tools (run_command) pulse this while they are alive so the+ * foreground heartbeat and the StallWatchdog do not abort a legitimate+ * ten-minute build as a "stalled provider". See core/progress-pulse.ts.+ */+ private installProgressPulse(): void {+ setProgressPulse(() => this.markProgress());+ }+private markProgress(activity?: string): void {this.lastProgressAt = Date.now();if (activity) {diff --git a/src/core/progress-pulse.ts b/src/core/progress-pulse.tsnew file mode 100644index 00000000..95a18523--- /dev/null+++ b/src/core/progress-pulse.ts@@ -0,0 +1,26 @@+/**+ * Progress pulse — lets long-running tools tell the agent "still alive".+ *+ * The foreground heartbeat and the StallWatchdog both watch the agent's+ * last-progress timestamp. Tools used to never touch it, so a legitimate+ * ten-minute build (run_command with timeout: 600) was aborted at four+ * minutes as a "stalled provider" and the child process kept running.+ * Tools call pulseProgress() while they are doing work; the agent installs+ * the hook once at construction.+ */+let hook: (() => void) | null = null;++export function setProgressPulse(fn: (() => void) | null): void {+ hook = fn;+}++export function pulseProgress(): void {+ try {+ hook?.();+ } catch {+ // A progress pulse must never break a tool.+ }+}++/** Interval at which a running tool re-pulses even without new output. */+export const TOOL_PULSE_INTERVAL_MS = 10_000;