Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(local-system): make a running shell command legible to the agent (#19703)

Arvin Xuc09343725e94
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index f121a4ec837..b7c403ea53a 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -420,6 +420,63 @@ describe('AgentRuntimeService', () => {
});
});
+ describe('determineCompletionReason', () => {
+ const reasonFor = (state: Record<string, any>) =>
+ (service as any).determineCompletionReason(state);
+
+ it('should report a plain completion as done', () => {
+ expect(reasonFor({ status: 'done', stepCount: 3 })).toBe('done');
+ });
+
+ // The guard finalizes the turn without tool calls, which is indistinguishable
+ // from a real answer by status alone β€” so these runs were all filed as 'done'
+ // and could not be counted.
+ it('should name a run the tool-call repeat guard cut short', () => {
+ expect(
+ reasonFor({
+ status: 'done',
+ stepCount: 250,
+ toolCallRepeatGuard: { counts: {}, stoppedByRepeatLimit: true },
+ }),
+ ).toBe('tool_call_repeat_limit');
+ });
+
+ it('should let a real failure outrank the repeat-guard marker', () => {
+ expect(
+ reasonFor({
+ status: 'error',
+ stepCount: 250,
+ toolCallRepeatGuard: { counts: {}, stoppedByRepeatLimit: true },
+ }),
+ ).toBe('error');
+ expect(
+ reasonFor({
+ status: 'interrupted',
+ stepCount: 250,
+ toolCallRepeatGuard: { counts: {}, stoppedByRepeatLimit: true },
+ }),
+ ).toBe('interrupted');
+ });
+
+ it('should ignore a guard that counted repeats without ever stopping', () => {
+ expect(
+ reasonFor({ status: 'done', stepCount: 3, toolCallRepeatGuard: { counts: { sig: 4 } } }),
+ ).toBe('done');
+ });
+
+ it('should still report the step and cost caps', () => {
+ expect(reasonFor({ status: 'running', maxSteps: 10, stepCount: 10 })).toBe('max_steps');
+ expect(
+ reasonFor({
+ status: 'running',
+ stepCount: 3,
+ cost: { total: 5 },
+ costLimit: { maxTotalCost: 5 },
+ }),
+ ).toBe('cost_limit');
+ });
+ });
+
describe('createOperation', () => {
const mockParams: OperationCreationParams = {
operationId: 'test-operation-1',
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index aa68787405c..9008983dbeb 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -4276,11 +4276,15 @@ export class AgentRuntimeService {
* Determine operation completion reason
*/
private determineCompletionReason(state: AgentState): StepCompletionReason {
- if (state.status === 'done') return 'done';
if (state.status === 'error') return 'error';
if (state.status === 'interrupted') return 'interrupted';
if (state.status === 'waiting_for_human') return 'waiting_for_human';
if (state.status === 'waiting_for_async_tool') return 'waiting_for_async_tool';
+ // Checked ahead of 'done' on purpose: a run the repeat guard cut short ends
+ // in exactly that status, having emitted a turn with no tool calls. Reading
+ // it as a plain 'done' is what made these runs uncountable.
+ if (state.toolCallRepeatGuard?.stoppedByRepeatLimit) return 'tool_call_repeat_limit';
+ if (state.status === 'done') return 'done';
if (state.maxSteps && state.stepCount >= state.maxSteps) return 'max_steps';
if (state.costLimit && state.cost?.total >= state.costLimit.maxTotalCost) return 'cost_limit';
return 'done';
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
index e1193041d9d..44fd58daf14 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
@@ -44,7 +44,10 @@ const log = debug('lobe-server:completion-lifecycle');
* `reason === 'done'` alone silently drops capped runs' artifacts.
*/
export const isSuccessLikeCompletionReason = (reason: string): boolean =>
- reason === 'done' || reason === 'max_steps' || reason === 'cost_limit';
+ reason === 'done' ||
+ reason === 'max_steps' ||
+ reason === 'cost_limit' ||
+ reason === 'tool_call_repeat_limit';
/**
* Triggers whose completion recalls the user with a push notification. Beyond
@@ -343,6 +346,7 @@ export class CompletionLifecycle {
const completionReason: any =
reason === 'max_steps' ||
reason === 'cost_limit' ||
+ reason === 'tool_call_repeat_limit' ||
reason === 'waiting_for_human' ||
reason === 'waiting_for_async_tool'
? reason
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index 2a4ec6c2459..63ebddec929 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -128,6 +128,7 @@ export type StepCompletionReason =
| 'interrupted'
| 'max_steps'
| 'cost_limit'
+ | 'tool_call_repeat_limit'
| 'waiting_for_human'
| 'waiting_for_async_tool';
diff --git a/apps/server/src/services/taskResultBridge/index.ts b/apps/server/src/services/taskResultBridge/index.ts
index bc0ac3fd4bb..b4b298fcb94 100644
--- a/apps/server/src/services/taskResultBridge/index.ts
+++ b/apps/server/src/services/taskResultBridge/index.ts
@@ -29,7 +29,8 @@ const FALLBACK_MAX_LENGTH = 2000;
const normalizeReason = (reason: string): CallbackReason => {
if (reason === 'interrupted') return 'interrupted';
if (reason === 'error') return 'error';
- // 'done' | 'max_steps' | 'cost_limit' | … β†’ treat as a normal completion.
+ // 'done' | 'max_steps' | 'cost_limit' | 'tool_call_repeat_limit' | … β†’
+ // treat as a normal completion.
return 'done';
};
diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
index 34f933fbc78..44f88c926b1 100644
--- a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
@@ -160,6 +160,27 @@ describe('callLlmFinalizer', () => {
type: 'stream_end',
}),
);
+ // The turn finalizes with no tool calls, so the run ends in `status: 'done'`
+ // like any other. This marker is the only thing that says it was cut short.
+ expect(result.newState.toolCallRepeatGuard?.stoppedByRepeatLimit).toBe(true);
+ });
+
+ it('keeps the repeat-limit marker on later turns that call no tools', async () => {
+ const state = AgentRuntime.createInitialState({ operationId: 'operation-1' });
+ state.toolCallRepeatGuard = { counts: {}, stoppedByRepeatLimit: true };
+
+ const result = await finalizeCallLlmTurn({
+ assistantMessageId: 'assistant-6',
+ events: [],
+ host: createHost(),
+ model: 'glm',
+ output: createOutput({ content: 'done' }),
+ provider: 'lobehub',
+ shouldReplayAssistantReasoning: false,
+ state,
+ });
+
+ expect(result.newState.toolCallRepeatGuard?.stoppedByRepeatLimit).toBe(true);
});
it('preserves user cancellation when an aborted stream emits the limit-th repeated tool call', async () => {
diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.ts
index a5fd6751353..a837085bbd6 100644
--- a/packages/agent-runtime/src/executors/callLlmFinalizer.ts
+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.ts
@@ -279,20 +279,27 @@ export const finalizeCallLlmTurn = async ({
stepLabel,
}: FinalizeCallLlmTurnInput): Promise<InstructionExecutionResult> => {
const { operation, transports } = host;
- const toolCallRepeatGuard = updateToolCallRepeatGuard(
- state.toolCallRepeatGuard,
- output.toolsCalling,
- );
- const finalizedOutput =
- output.finishReason !== 'abort' && hasRepeatedToolCall(toolCallRepeatGuard)
- ? {
- ...output,
- content: `Stopped after the same tool call was requested ${TOOL_CALL_REPEAT_LIMIT} consecutive times.`,
- finishReason: 'tool_call_repeat_limit',
- toolCalls: [],
- toolsCalling: [],
- }
- : output;
+ const repeatCounts = updateToolCallRepeatGuard(state.toolCallRepeatGuard, output.toolsCalling);
+ const stoppedByRepeatLimit = output.finishReason !== 'abort' && hasRepeatedToolCall(repeatCounts);
+ // Carried on the state so the terminal reason can name this stop. Sticky once
+ // set: later turns emit no tool calls, and `updateToolCallRepeatGuard` resets
+ // its counts on those, which would otherwise erase the only trace of why the
+ // run ended.
+ const toolCallRepeatGuard = {
+ ...repeatCounts,
+ ...((stoppedByRepeatLimit || state.toolCallRepeatGuard?.stoppedByRepeatLimit) && {
+ stoppedByRepeatLimit: true,
+ }),
+ };
+ const finalizedOutput = stoppedByRepeatLimit
+ ? {
+ ...output,
+ content: `Stopped after the same tool call was requested ${TOOL_CALL_REPEAT_LIMIT} consecutive times.`,
+ finishReason: 'tool_call_repeat_limit',
+ toolCalls: [],
+ toolsCalling: [],
+ }
+ : output;
events.push({
result: {
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index d799245eabf..1cbd4edcc54 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -461,6 +461,14 @@ export interface AgentState {
*/
toolCallRepeatGuard?: {
counts: Record<string, number>;
+ /**
+ * Set on the turn the guard cut short. The run still lands in `status:
+ * 'done'` β€” the turn was finalized without tool calls, which is what
+ * finishing looks like β€” so without this marker a loop-death is
+ * indistinguishable from a real answer, and nothing downstream can count
+ * how often the guard fires.
+ */
+ stoppedByRepeatLimit?: boolean;
};
/**
diff --git a/packages/agent-tracing/src/types.ts b/packages/agent-tracing/src/types.ts
index ad8e61f7793..235d200e8be 100644
--- a/packages/agent-tracing/src/types.ts
+++ b/packages/agent-tracing/src/types.ts
@@ -2,7 +2,13 @@ export interface ExecutionSnapshot {
agentId?: string;
completedAt?: number;
completionReason?:
- 'done' | 'error' | 'interrupted' | 'max_steps' | 'cost_limit' | 'waiting_for_human';
+ | 'done'
+ | 'error'
+ | 'interrupted'
+ | 'max_steps'
+ | 'cost_limit'
+ | 'tool_call_repeat_limit'
+ | 'waiting_for_human';
error?: { type: string; message: string };
externalRetryCount?: number;
model?: string;
diff --git a/packages/builtin-tool-local-system/src/manifest.ts b/packages/builtin-tool-local-system/src/manifest.ts
index beb1d47b743..d443d11bcfa 100644
--- a/packages/builtin-tool-local-system/src/manifest.ts
+++ b/packages/builtin-tool-local-system/src/manifest.ts
@@ -231,7 +231,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {
{
defaultTimeoutMs: 60_000,
description:
- 'Start a terminal session to execute a shell command and return console output collected during the wait window (up to 60 seconds by default). If the command is still running after the wait window, the result includes `shell_id` for later observation or termination.',
+ 'Start a terminal session to execute a shell command and return console output collected during the wait window (60 seconds by default, up to 600000ms via `timeout`). If the command is still running after the wait window, the result includes `shell_id` for later observation or termination.',
humanIntervention: 'required',
name: LocalSystemApiName.runCommand,
parameters: {
@@ -256,6 +256,11 @@ export const LocalSystemManifest: BuiltinToolManifest = {
'Set to true to return immediately after starting the terminal session. The result will include a `shell_id` for later observation or termination.',
type: 'boolean',
},
+ timeout: {
+ description:
+ 'How long to wait for the command, in milliseconds (default 60000, max 600000). Does not kill the command when it elapses β€” the result carries a `shell_id` you can keep observing. Size it to the work: a test suite or build deserves a long single wait rather than a series of short ones.',
+ type: 'number',
+ },
},
required: ['description', 'command'],
type: 'object',
@@ -264,7 +269,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {
{
defaultTimeoutMs: 60_000,
description:
- 'Retrieve output from a running or completed background shell command. Waits for one output window (up to 60 seconds by default).',
+ 'Retrieve output from a running or completed background shell command. Blocks until the command exits or `timeout` elapses, then reports whether it is still running. Prefer one long wait over repeated short polls.',
name: LocalSystemApiName.getCommandOutput,
parameters: {
properties: {
@@ -277,6 +282,11 @@ export const LocalSystemManifest: BuiltinToolManifest = {
description: 'The ID of the background shell to retrieve output from',
type: 'string',
},
+ timeout: {
+ description:
+ 'How long to wait for the command to exit, in milliseconds (default 60000, max 600000). Does not kill the command when it elapses. Raise it instead of calling this repeatedly β€” each call is a full model turn, so ten 60s polls cost ten turns to learn what one 600s wait reports once.',
+ type: 'number',
+ },
},
required: ['shell_id'],
type: 'object',
diff --git a/packages/builtin-tool-local-system/src/systemRole.desktop.ts b/packages/builtin-tool-local-system/src/systemRole.desktop.ts
index 15d25a4d61f..4ea0050f63c 100644
--- a/packages/builtin-tool-local-system/src/systemRole.desktop.ts
+++ b/packages/builtin-tool-local-system/src/systemRole.desktop.ts
@@ -79,6 +79,7 @@ You have access to a set of tools to interact with the user's local file system:
- 'command': The shell command to execute.
- 'description' (Optional but recommended): A clear, concise description of what the command does (5-10 words, in active voice). **IMPORTANT: Always use the same language as the user's input.** If the user speaks Chinese, write the description in Chinese; if English, use English, etc.
- 'run_in_background' (Optional): Set to true to return immediately after starting the terminal session. The result includes a 'shell_id' for later observation or termination.
+ - 'timeout' (Optional): How long to wait for the command, in milliseconds (default 60000, max 600000). It does not kill the command when it elapses. Size it to the work β€” a build or test suite is worth one long wait.
The command runs in {{defaultShell}}. {{shellSyntaxGuidance}} The returned output reflects the tool's wait window, not necessarily the full command lifetime.
- Installing software: do NOT proactively install software on the user's system. Prefer tools that are already installed, or a no-install alternative. If a task genuinely needs a system-level or global install (e.g. \`brew install\`, \`apt\`/\`dnf install\`, \`npm i -g\`, \`pipx\`, a global \`pip install\`), ask the user first and explain why, rather than running the install on your own. Routine project-local dependency installs (e.g. \`npm\`/\`pnpm install\` inside a project, \`pip install\` inside an active virtualenv) are fine β€” run them as normal.
- Result semantics:
@@ -86,8 +87,9 @@ You have access to a set of tools to interact with the user's local file system:
- 'shell_id' identifies the terminal session for later observation/termination.
- For retrieving output from terminal sessions: Use 'getCommandOutput'. Provide:
- 'shell_id': The ID returned from runCommand.
- - 'filter' (Optional): A regex pattern to filter output lines.
- Returns a current output snapshot.
+ - 'filter' (Optional): A regex pattern to filter output lines. When the filter matches nothing the result says so β€” that is not the same as the command having written nothing.
+ - 'timeout' (Optional): How long to wait for the command to exit, in milliseconds (default 60000, max 600000).
+ It blocks until the command exits or 'timeout' elapses, and the result always states which of the two happened. Wait once for as long as the work deserves instead of polling: every call is a full turn of yours, so ten 60-second polls buy the same answer as one 600-second wait at ten times the cost. If a result repeats unchanged, re-reading it will not change it β€” wait longer, look at the output files directly, or kill the session.
- For killing running terminal sessions: Use 'killCommand' with 'shell_id'.
Treat terminal sessions as ongoing resources: when elapsed wait time and observed progress no longer match the command's expected lifecycle, reassess whether the session should continue running.
- For searching content in files: Use 'grepContent'. Provide:
diff --git a/packages/builtin-tool-local-system/src/systemRole.ts b/packages/builtin-tool-local-system/src/systemRole.ts
index 669d4a2a2b5..a1761588a0c 100644
--- a/packages/builtin-tool-local-system/src/systemRole.ts
+++ b/packages/builtin-tool-local-system/src/systemRole.ts
@@ -77,6 +77,7 @@ You have access to a set of tools to interact with the user's local file system:
- 'command': The shell command to execute.
- 'description' (Optional but recommended): A clear, concise description of what the command does (5-10 words, in active voice). **IMPORTANT: Always use the same language as the user's input.** If the user speaks Chinese, write the description in Chinese; if English, use English, etc.
- 'run_in_background' (Optional): Set to true to return immediately after starting the terminal session. The result includes a 'shell_id' for later observation or termination.
+ - 'timeout' (Optional): How long to wait for the command, in milliseconds (default 60000, max 600000). It does not kill the command when it elapses. Size it to the work β€” a build or test suite is worth one long wait.
The command runs in {{defaultShell}}. {{shellSyntaxGuidance}} The returned output reflects the tool's wait window, not necessarily the full command lifetime.
- Installing software: do NOT proactively install software on the user's system. Prefer tools that are already installed, or a no-install alternative. If a task genuinely needs a system-level or global install (e.g. \`brew install\`, \`apt\`/\`dnf install\`, \`npm i -g\`, \`pipx\`, a global \`pip install\`), ask the user first and explain why, rather than running the install on your own. Routine project-local dependency installs (e.g. \`npm\`/\`pnpm install\` inside a project, \`pip install\` inside an active virtualenv) are fine β€” run them as normal.
- Result semantics:
@@ -84,8 +85,9 @@ You have access to a set of tools to interact with the user's local file system:
- 'shell_id' identifies the terminal session for later observation/termination.
- For retrieving output from terminal sessions: Use 'getCommandOutput'. Provide:
- 'shell_id': The ID returned from runCommand.
- - 'filter' (Optional): A regex pattern to filter output lines.
- Returns a current output snapshot.
+ - 'filter' (Optional): A regex pattern to filter output lines. When the filter matches nothing the result says so β€” that is not the same as the command having written nothing.
+ - 'timeout' (Optional): How long to wait for the command to exit, in milliseconds (default 60000, max 600000).
+ It blocks until the command exits or 'timeout' elapses, and the result always states which of the two happened. Wait once for as long as the work deserves instead of polling: every call is a full turn of yours, so ten 60-second polls buy the same answer as one 600-second wait at ten times the cost. If a result repeats unchanged, re-reading it will not change it β€” wait longer, look at the output files directly, or kill the session.
- For killing running terminal sessions: Use 'killCommand' with 'shell_id'.
Treat terminal sessions as ongoing resources: when elapsed wait time and observed progress no longer match the command's expected lifecycle, reassess whether the session should continue running.
- For searching content in files: Use 'grepContent'. Provide:
diff --git a/packages/local-file-shell/src/shell/__tests__/process-manager.test.ts b/packages/local-file-shell/src/shell/__tests__/process-manager.test.ts
index c5674409b97..86892f99418 100644
--- a/packages/local-file-shell/src/shell/__tests__/process-manager.test.ts
+++ b/packages/local-file-shell/src/shell/__tests__/process-manager.test.ts
@@ -7,7 +7,7 @@ import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { ShellProcess } from '../process-manager';
-import { ShellProcessManager } from '../process-manager';
+import { MAX_OBSERVATION_TIMEOUT_MS, ShellProcessManager } from '../process-manager';
function createMockProcess(exitCode: number | null = null, pid?: number): ChildProcess {
const process = new EventEmitter() as ChildProcess;
@@ -128,7 +128,10 @@ describe('ShellProcessManager', () => {
}
});
- it('should wait up to the default observation timeout when timeout is omitted', async () => {
+ // `timeout` is the budget for the whole call, not for the wait alone: the
+ // dispatcher derives its deadline from the same number, so the wait has to
+ // end early enough to read the output files and answer inside it.
+ it('should reserve headroom out of the default observation budget', async () => {
vi.useFakeTimers();
try {
const process = createMockProcess();
@@ -141,7 +144,7 @@ describe('ShellProcessManager', () => {
return result;
});
- await vi.advanceTimersByTimeAsync(59_999);
+ await vi.advanceTimersByTimeAsync(54_999);
expect(resolved).toBe(false);
await vi.advanceTimersByTimeAsync(1);
@@ -153,6 +156,189 @@ describe('ShellProcessManager', () => {
}
});
+ it('should reserve the same headroom out of an explicit budget', async () => {
+ vi.useFakeTimers();
+ try {
+ const process = createMockProcess();
+ const shellProcess = createShellProcess(manager, 'test-1', process);
+ manager.register('test-1', shellProcess);
+ let resolved = false;
+
+ const pending = manager
+ .getOutput({ shell_id: 'test-1', timeout: 300_000 })
+ .then((result) => {
+ resolved = true;
+ return result;
+ });
+
+ await vi.advanceTimersByTimeAsync(294_999);
+ expect(resolved).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(1);
+ await pending;
+ expect(resolved).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ // The renderer's client executor abandons the call 500ms before the same
+ // budget expires, so a small budget that waits all the way to the end is
+ // aborted instead of answering. The floor keeps the margin above that.
+ it('should keep headroom on a small explicit budget', async () => {
+ vi.useFakeTimers();
+ try {
+ const process = createMockProcess();
+ const shellProcess = createShellProcess(manager, 'test-1', process);
+ manager.register('test-1', shellProcess);
+ let resolved = false;
+
+ const pending = manager.getOutput({ shell_id: 'test-1', timeout: 2000 }).then((result) => {
+ resolved = true;
+ return result;
+ });
+
+ await vi.advanceTimersByTimeAsync(1399);
+ expect(resolved).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(1);
+ await pending;
+ expect(resolved).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ // Continuous and monotonic: no budget may buy a shorter wait than a smaller
+ // one. The earlier subtract-a-constant form fell off a cliff, handing 5000ms
+ // a 5000ms wait and 5001ms a 1ms wait.
+ it('should never shorten the wait as the budget grows', async () => {
+ const waits: number[] = [];
+ vi.useFakeTimers();
+ try {
+ for (const budget of [200, 1000, 1200, 2000, 5000, 5001, 6000, 20_000, 60_000]) {
+ const process = createMockProcess();
+ const shellProcess = createShellProcess(manager, `b-${budget}`, process);
+ manager.register(`b-${budget}`, shellProcess);
+
+ let waited = 0;
+ const pending = manager.getOutput({ shell_id: `b-${budget}`, timeout: budget });
+ // Walk the clock forward until the observation gives up.
+ for (let step = 0; step < budget + 10; step += 100) {
+ await vi.advanceTimersByTimeAsync(100);
+ waited = step + 100;
+ if (await Promise.race([pending.then(() => true), Promise.resolve(false)])) break;
+ }
+ await pending;
+ waits.push(waited);
+ }
+ } finally {
+ vi.useRealTimers();
+ }
+
+ expect(waits).toEqual([...waits].sort((a, b) => a - b));
+ });
+
+ // A signal-terminated child exits without an exit code. Callers that read
+ // liveness off `exit_code` alone therefore describe a command the agent
+ // just killed as still running, and go on waiting for it.
+ it('should report a signal-terminated command as finished, with the signal', async () => {
+ const process = createMockProcess();
+ const shellProcess = createShellProcess(manager, 'test-1', process);
+ manager.register('test-1', shellProcess);
+
+ Object.defineProperty(process, 'signalCode', {
+ configurable: true,
+ value: 'SIGKILL',
+ writable: true,
+ });
+ process.emit('exit', null, 'SIGKILL');
+ process.emit('close', null, 'SIGKILL');
+
+ const result = await manager.getOutput({ shell_id: 'test-1' });
+
+ expect(result.exit_code).toBeUndefined();
+ expect(result.running).toBe(false);
+ expect(result.signal).toBe('SIGKILL');
+ });
+
+ it('should report a live command as running', async () => {
+ const process = createMockProcess();
+ manager.register('test-1', createShellProcess(manager, 'test-1', process));
+
+ const result = await manager.getOutput({ shell_id: 'test-1', timeout: 200 });
+
+ expect(result.exit_code).toBeUndefined();
+ expect(result.running).toBe(true);
+ expect(result.signal).toBeUndefined();
+ });
+
+ it('should report an exited command as finished', async () => {
+ const process = createMockProcess();
+ manager.register('test-1', createShellProcess(manager, 'test-1', process));
+
+ (process as { exitCode: number | null }).exitCode = 0;
+ process.emit('exit', 0);
+ process.emit('close', 0);
+
+ const result = await manager.getOutput({ shell_id: 'test-1' });
+
+ expect(result.exit_code).toBe(0);
+ expect(result.running).toBe(false);
+ });
+
+ // Below the dispatcher's 1s minimum there is no transport margin to
+ // protect, so a deliberate short peek still waits β€” for half its budget.
+ it('should still wait on a budget smaller than the headroom floor', async () => {
+ vi.useFakeTimers();
+ try {
+ const process = createMockProcess();
+ const shellProcess = createShellProcess(manager, 'test-1', process);
+ manager.register('test-1', shellProcess);
+ let resolved = false;
+
+ const pending = manager.getOutput({ shell_id: 'test-1', timeout: 400 }).then(() => {
+ resolved = true;
+ });
+
+ await vi.advanceTimersByTimeAsync(199);
+ expect(resolved).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(1);
+ await pending;
+ expect(resolved).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('should clamp a request above the ceiling to the ceiling', async () => {
+ vi.useFakeTimers();
+ try {
+ const process = createMockProcess();
+ const shellProcess = createShellProcess(manager, 'test-1', process);
+ manager.register('test-1', shellProcess);
+ let resolved = false;
+
+ const pending = manager
+ .getOutput({ shell_id: 'test-1', timeout: MAX_OBSERVATION_TIMEOUT_MS * 10 })
+ .then((result) => {
+ resolved = true;
+ return result;
+ });
+
+ await vi.advanceTimersByTimeAsync(MAX_OBSERVATION_TIMEOUT_MS - 5001);
+ // 600_000 βˆ’ the 5000ms headroom ceiling.
+ expect(resolved).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(1);
+ await pending;
+ expect(resolved).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('should return done when process exits before new output', async () => {
const process = createMockProcess();
manager.register('test-1', createShellProcess(manager, 'test-1', process));
diff --git a/packages/local-file-shell/src/shell/process-manager.ts b/packages/local-file-shell/src/shell/process-manager.ts
index 470e6e8849c..090366a7fe5 100644
--- a/packages/local-file-shell/src/shell/process-manager.ts
+++ b/packages/local-file-shell/src/shell/process-manager.ts
@@ -10,7 +10,58 @@ import { decodeClixml } from './clixml';
import { buildOutputPreview } from './utils';
export const DEFAULT_OBSERVATION_TIMEOUT_MS = 60_000;
-const MAX_OBSERVATION_TIMEOUT_MS = 120_000;
+/**
+ * Ceiling on a single observation window. Sized for the real unit of work an
+ * agent waits on β€” a test suite, a build, an install β€” because the alternative
+ * to waiting once is polling, and every poll costs a full LLM turn with the
+ * whole conversation replayed into it. Stays well inside the dispatcher's own
+ * ceiling (`MAX_TIMEOUT_MS`, 800s) so the wait can never outlive the call
+ * carrying it.
+ */
+export const MAX_OBSERVATION_TIMEOUT_MS = 600_000;
+/**
+ * Slice held back from the caller's budget. The same `timeout` value sets the
+ * dispatcher's deadline *and* this wait, and after the wait we still have to
+ * drain the pipes, read the output files and make the trip home β€” so a wait
+ * that spent the entire budget would be aborted right as it produced an answer,
+ * charging the agent the full wait for nothing.
+ *
+ * Proportional, with both ends pinned. The floor is what the transport alone
+ * costs: the renderer's client executor gives up 500ms before the server's
+ * deadline (`clientToolExecution`'s `SAFETY_BUFFER_MS`), so anything less than
+ * that is budget we never had. The ceiling keeps a ten-minute wait from
+ * surrendering a minute of itself.
+ */
+const OBSERVATION_TIMEOUT_HEADROOM_RATIO = 0.1;
+const MIN_OBSERVATION_TIMEOUT_HEADROOM_MS = 600;
+const MAX_OBSERVATION_TIMEOUT_HEADROOM_MS = 5_000;
+
+/**
+ * The margin never eats more than half the budget. Below the dispatcher's
+ * minimum (`MIN_TIMEOUT_MS`, 1s) there is no transport left to protect β€” such a
+ * budget only ever arrives from an in-process caller asking for a short,
+ * deliberate peek, and a peek that never waits is not a peek.
+ */
+const MAX_OBSERVATION_TIMEOUT_HEADROOM_RATIO = 0.5;
+
+/**
+ * What is left of `budget` once the trip home is paid for. Continuous and
+ * monotonic in `budget` β€” a caller that asks for more must never get a shorter
+ * wait, which is what a subtract-a-constant margin fails at around its own
+ * threshold.
+ */
+const resolveWaitTimeout = (budget: number): number => {
+ const headroom = Math.min(
+ Math.max(
+ Math.ceil(budget * OBSERVATION_TIMEOUT_HEADROOM_RATIO),
+ MIN_OBSERVATION_TIMEOUT_HEADROOM_MS,
+ ),
+ MAX_OBSERVATION_TIMEOUT_HEADROOM_MS,
+ budget * MAX_OBSERVATION_TIMEOUT_HEADROOM_RATIO,
+ );
+
+ return Math.max(budget - headroom, 0);
+};
const RUN_COMMAND_HEAD_RATIO = 0.2;
const GET_COMMAND_OUTPUT_HEAD_RATIO = 0;
const OUTPUT_PREVIEW_TOTAL_MAX_BYTES = 22 * 1024;
@@ -145,6 +196,7 @@ export class ShellProcessManager {
return {
error: `Shell ID ${shell_id} not found`,
output: '',
+ running: false,
stderr: '',
stdout: '',
success: false,
@@ -158,10 +210,11 @@ export class ShellProcessManager {
// and its 'exit' event has already fired β€” waiting would just burn the
// full observation timeout before returning the killed command's output.
if (exitCode === null && childProcess.signalCode == null) {
- const waitTimeout =
+ const budget =
typeof timeout === 'number' && Number.isFinite(timeout)
? Math.min(Math.max(Math.trunc(timeout), 0), MAX_OBSERVATION_TIMEOUT_MS)
: DEFAULT_OBSERVATION_TIMEOUT_MS;
+ const waitTimeout = resolveWaitTimeout(budget);
if (waitTimeout > 0) {
let timer: ReturnType<typeof setTimeout> | undefined;
@@ -233,10 +286,20 @@ export class ShellProcessManager {
const startedAt = shellProcess.startedAt ?? Date.now();
const durationMs = Math.max(0, (shellProcess.endedAt ?? Date.now()) - startedAt);
+ // Liveness is reported, not inferred. A missing `exit_code` does not mean
+ // "still working": a signal-terminated child (`kill` on POSIX) exits
+ // without one, and so does a child that failed to spawn. Leaving the caller
+ // to guess from `exit_code` alone is how a killed session gets described as
+ // still running.
+ const signal = childProcess.signalCode ?? undefined;
+ const running = exitCode === null && !signal && !shellProcess.spawnError;
+
return {
duration_ms: durationMs,
error: shellProcess.spawnError?.message,
exit_code: shellProcess.spawnError ? undefined : (exitCode ?? undefined),
+ running,
+ signal,
output: stdout + stderr,
output_files: {
stderr: {
diff --git a/packages/local-file-shell/src/types.ts b/packages/local-file-shell/src/types.ts
index 74abafb1c58..c270fc2d0d9 100644
--- a/packages/local-file-shell/src/types.ts
+++ b/packages/local-file-shell/src/types.ts
@@ -17,9 +17,10 @@ export interface RunCommandResult {
duration_ms?: number;
error?: string;
/**
- * Present only after the command has exited.
+ * Present only after the command has exited *normally*.
* `0` means success, non-zero means the command finished with an error.
- * `undefined` means the command is still running.
+ * Absent while the command runs β€” but also when it was killed by a signal or
+ * never spawned, so it cannot stand in for liveness. Read `running`.
*/
exit_code?: number;
output?: string;
@@ -27,6 +28,11 @@ export interface RunCommandResult {
stderr: { path: string; size: number; truncated: boolean };
stdout: { path: string; size: number; truncated: boolean };
};
+ /**
+ * Whether the command was still executing when the wait window closed.
+ * Absent for a `run_in_background` start, which returns before observing.
+ */
+ running?: boolean;
/**
* Whether this command was actually confined by the device sandbox.
*
@@ -44,11 +50,13 @@ export interface RunCommandResult {
* that can be resumed with `getCommandOutput`.
*/
shell_id?: string;
+ /** The signal that terminated the command, when one did (POSIX). */
+ signal?: string;
stderr?: string;
stdout?: string;
/**
* True when the command/session request completed successfully.
- * Use `exit_code` to determine whether the underlying command has exited.
+ * Use `running` to determine whether the underlying command has finished.
*/
success: boolean;
}
@@ -72,9 +80,10 @@ export interface GetCommandOutputResult {
duration_ms?: number;
error?: string;
/**
- * Present only after the command has exited.
+ * Present only after the command has exited *normally*.
* `0` means success, non-zero means the command finished with an error.
- * `undefined` means the command is still running.
+ * Absent while the command runs β€” but also when it was killed by a signal or
+ * never spawned, so it cannot stand in for liveness. Read `running`.
*/
exit_code?: number;
output: string;
@@ -82,11 +91,20 @@ export interface GetCommandOutputResult {
stderr: { path: string; size: number; truncated: boolean };
stdout: { path: string; size: number; truncated: boolean };
};
+ /**
+ * Whether the command was still executing when this observation was taken.
+ * The authoritative liveness signal: the three ways a command can be finished
+ * (exited, signalled, failed to spawn) do not share a single field, and only
+ * this side can see all of them.
+ */
+ running: boolean;
+ /** The signal that terminated the command, when one did (POSIX). */
+ signal?: string;
stderr: string;
stdout: string;
/**
* True when the output request completed successfully.
- * Use `exit_code` to determine whether the underlying command has exited.
+ * Use `running` to determine whether the underlying command has finished.
*/
success: boolean;
}
diff --git a/packages/prompts/src/prompts/fileSystem/formatCommandOutput.test.ts b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.test.ts
index eff09534919..ef0e8e2b33f 100644
--- a/packages/prompts/src/prompts/fileSystem/formatCommandOutput.test.ts
+++ b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.test.ts
@@ -3,19 +3,25 @@ import { describe, expect, it } from 'vitest';
import { formatCommandOutput } from './formatCommandOutput';
describe('formatCommandOutput', () => {
- it('should format successful output without exit code', () => {
+ it('should format successful output without a reported lifecycle', () => {
const result = formatCommandOutput({
success: true,
});
expect(result).toMatchInlineSnapshot(`"Output retrieved."`);
});
- it('should suppress zero exit code when present', () => {
+ it('should state completion when the command exited cleanly', () => {
const result = formatCommandOutput({
exitCode: 0,
+ output: 'all good',
success: true,
});
- expect(result).toMatchInlineSnapshot(`"Output retrieved."`);
+ expect(result).toMatchInlineSnapshot(`
+ "Command completed successfully.
+
+ Output:
+ all good"
+ `);
});
it('should format duration in seconds when present', () => {
@@ -38,9 +44,7 @@ describe('formatCommandOutput', () => {
success: true,
});
expect(result).toMatchInlineSnapshot(`
- "Output retrieved.
-
- Exit code: 17
+ "Command failed with exit code 17
Duration: 123s
@@ -65,9 +69,7 @@ describe('formatCommandOutput', () => {
success: true,
});
expect(result).toMatchInlineSnapshot(`
- "Output retrieved.
-
- Exit code: 1
+ "Command failed with exit code 1
Output:
Some output
@@ -145,17 +147,153 @@ describe('formatCommandOutput', () => {
`);
});
- it('should not special-case missing exit code when formatting output', () => {
+ // A still-running observation and a finished-but-silent one carry the exact
+ // same fields: empty output, a 0-byte log, a duration. Only the header tells
+ // them apart, so both renders are pinned here.
+ describe('lifecycle is always stated', () => {
+ it('should say the command is still running and how to wait for it', () => {
+ const result = formatCommandOutput({
+ canWaitLonger: true,
+ durationMs: 137_421,
+ outputFiles: {
+ stdout: { path: '/tmp/lobehub-shell/sh-197/stdout.log', size: 0, truncated: false },
+ },
+ running: true,
+ shellId: 'sh-197',
+ success: true,
+ });
+
+ expect(result).toMatchInlineSnapshot(`
+ "Command is still running.
+ shell_id: sh-197
+
+ Pass a larger \`timeout\` (ms) to wait for it within a single call instead of polling repeatedly; \`killCommand\` ends the session.
+
+ Elapsed: 137s
+
+ Full stdout saved to: /tmp/lobehub-shell/sh-197/stdout.log (0 bytes)
+
+ (no output yet)"
+ `);
+ });
+
+ it('should not render the same way once the command has exited silently', () => {
+ const result = formatCommandOutput({
+ durationMs: 281_914,
+ exitCode: 0,
+ outputFiles: {
+ stdout: { path: '/tmp/lobehub-shell/sh-197/stdout.log', size: 0, truncated: false },
+ },
+ running: false,
+ shellId: 'sh-197',
+ success: true,
+ });
+
+ expect(result).toMatchInlineSnapshot(`
+ "Command completed successfully.
+
+ Duration: 282s
+
+ Full stdout saved to: /tmp/lobehub-shell/sh-197/stdout.log (0 bytes)
+
+ (no output)"
+ `);
+ });
+
+ it('should omit the shell id when the caller did not supply one', () => {
+ const result = formatCommandOutput({
+ canWaitLonger: true,
+ running: true,
+ success: true,
+ });
+
+ expect(result).toMatchInlineSnapshot(`
+ "Command is still running.
+
+ Pass a larger \`timeout\` (ms) to wait for it within a single call instead of polling repeatedly; \`killCommand\` ends the session.
+
+ (no output yet)"
+ `);
+ });
+
+ // A signal-killed command exits without an exit code, so inferring liveness
+ // from that alone describes a command the agent just killed as still going.
+ it('should name the signal that ended a terminated command', () => {
+ const result = formatCommandOutput({
+ canWaitLonger: true,
+ durationMs: 4_000,
+ outputFiles: {
+ stdout: { path: '/tmp/lobehub-shell/sh-12/stdout.log', size: 0, truncated: false },
+ },
+ running: false,
+ shellId: 'sh-12',
+ signal: 'SIGKILL',
+ success: true,
+ });
+
+ expect(result).toMatchInlineSnapshot(`
+ "Command was terminated by SIGKILL
+
+ Duration: 4s
+
+ Full stdout saved to: /tmp/lobehub-shell/sh-12/stdout.log (0 bytes)
+
+ (no output)"
+ `);
+ expect(result).not.toContain('still running');
+ });
+
+ // A backend whose schema has no `timeout` must not be told to raise one.
+ it('should not advise a longer wait the backend cannot offer', () => {
+ const result = formatCommandOutput({
+ running: true,
+ shellId: 'cmd-1',
+ success: true,
+ });
+
+ expect(result).toMatchInlineSnapshot(`
+ "Command is still running.
+ shell_id: cmd-1
+
+ Give it time before checking again; \`killCommand\` ends the session.
+
+ (no output yet)"
+ `);
+ });
+ });
+
+ it('should attribute an empty render to the filter when the log is not empty', () => {
const result = formatCommandOutput({
- output: 'still running',
+ exitCode: 0,
+ filter: 'Test Files|FAIL',
+ outputFiles: {
+ stdout: { path: '/tmp/lobehub-shell/sh-197/stdout.log', size: 925, truncated: false },
+ },
+ running: false,
success: true,
});
expect(result).toMatchInlineSnapshot(`
- "Output retrieved.
+ "Command completed successfully.
- Output:
- still running"
+ Full stdout saved to: /tmp/lobehub-shell/sh-197/stdout.log (925 bytes)
+
+ (filter "Test Files|FAIL" matched no lines β€” call again without \`filter\` to see the raw output)"
`);
});
+
+ it('should not blame the filter when the command genuinely wrote nothing', () => {
+ const result = formatCommandOutput({
+ exitCode: 0,
+ filter: 'anything',
+ outputFiles: {
+ stdout: { path: '/tmp/lobehub-shell/sh-197/stdout.log', size: 0, truncated: false },
+ },
+ running: false,
+ success: true,
+ });
+
+ expect(result).toContain('(no output)');
+ expect(result).not.toContain('matched no lines');
+ });
});
diff --git a/packages/prompts/src/prompts/fileSystem/formatCommandOutput.ts b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.ts
index b01b6211e3c..82b797d386f 100644
--- a/packages/prompts/src/prompts/fileSystem/formatCommandOutput.ts
+++ b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.ts
@@ -1,12 +1,34 @@
export interface FormatCommandOutputParams {
+ /**
+ * Whether this backend's `getCommandOutput` schema actually offers a
+ * `timeout`. Off by default: advising the reader to wait longer in one call
+ * is worse than silence when the tool it is holding cannot do that.
+ */
+ canWaitLonger?: boolean;
durationMs?: number;
error?: string;
exitCode?: number;
+ /**
+ * The regex the caller applied to the output lines, when it applied one. Only
+ * used to explain an empty render: filtered-to-nothing and wrote-nothing are
+ * otherwise the same blank result.
+ */
+ filter?: string;
output?: string;
outputFiles?: {
stderr?: { path: string; size?: number; truncated?: boolean };
stdout?: { path: string; size?: number; truncated?: boolean };
};
+ /**
+ * Whether the command was still executing at observation time. Resolved by the
+ * caller (which knows the service's own lifecycle reporting) rather than
+ * inferred here, so a service that reports liveness directly is believed.
+ */
+ running?: boolean;
+ /** Session id to poll or kill, echoed back so a still-running result is actionable. */
+ shellId?: string;
+ /** The signal that terminated the command, when one did. */
+ signal?: string;
stderr?: string;
stdout?: string;
success: boolean;
@@ -28,22 +50,67 @@ export const formatCommandOutputFileSize = (size?: number): string => {
return `${gb.toFixed(1).replace(/\.0$/, '')}GB`;
};
+/**
+ * Render one observation of a shell session for the model.
+ *
+ * The header has to state the lifecycle, because every other field reads the
+ * same in both states: a command still buffering its first byte and a command
+ * that exited 0 having printed nothing both produce an empty output and a
+ * 0-byte log. Left unstated, the reader's only way to tell them apart is to go
+ * hunting through `ps`/`pgrep` β€” or to poll the same session until a repeat
+ * guard cuts it off. `formatCommandResult` (the `runCommand` side) has always
+ * named the state; this is the same vocabulary so both tools read alike.
+ */
export const formatCommandOutput = ({
+ canWaitLonger,
durationMs,
success,
exitCode,
+ filter,
output,
outputFiles,
+ running,
+ shellId,
+ signal,
stderr,
stdout,
error,
}: FormatCommandOutputParams): string => {
- const message = success ? 'Output retrieved.' : `Failed: ${error}`;
+ const hasNonZeroExit = exitCode !== undefined && exitCode !== 0;
+
+ const header = (): string => {
+ // `success` is the envelope β€” the observation came back. It says nothing
+ // about the command, which is what `running`/`exitCode` are for.
+ if (!success) return `Failed: ${error}`;
+ if (running) {
+ const lines = ['Command is still running.'];
+ if (shellId) lines.push(`shell_id: ${shellId}`);
+ return lines.join('\n');
+ }
+ if (hasNonZeroExit) return `Command failed with exit code ${exitCode}`;
+ if (exitCode === 0) return 'Command completed successfully.';
+ // Finished without an exit code β€” killed. Naming the signal matters: the
+ // agent usually sent it, and "terminated" answers a question that
+ // "Output retrieved." leaves open.
+ if (signal) return `Command was terminated by ${signal}`;
+ // No lifecycle reported at all: say only what we know.
+ return 'Output retrieved.';
+ };
+
+ const parts: string[] = [header()];
+
+ if (success && running) {
+ parts.push(
+ canWaitLonger
+ ? 'Pass a larger `timeout` (ms) to wait for it within a single call instead of polling repeatedly; `killCommand` ends the session.'
+ : 'Give it time before checking again; `killCommand` ends the session.',
+ );
+ }
- const parts: string[] = [message];
- if (exitCode !== undefined && exitCode !== 0) parts.push(`Exit code: ${exitCode}`);
if (durationMs !== undefined && Number.isFinite(durationMs)) {
- parts.push(`Duration: ${formatDuration(durationMs)}`);
+ // The same field means elapsed-so-far while running and total once exited.
+ const elapsed = formatDuration(durationMs);
+ parts.push(running ? `Elapsed: ${elapsed}` : `Duration: ${elapsed}`);
}
if (outputFiles?.stdout?.path) {
const size = formatCommandOutputFileSize(outputFiles.stdout.size);
@@ -66,5 +133,20 @@ export const formatCommandOutput = ({
if (stderr) parts.push(`Stderr:\n${stderr}`);
if (error && success) parts.push(`Error: ${error}`);
+ // Nothing rendered above the fold has to be explained, or silence gets read
+ // as a clean run. Three different causes look identical without this.
+ if (!output && !stdout && !stderr) {
+ const bytesOnDisk = (outputFiles?.stdout?.size ?? 0) + (outputFiles?.stderr?.size ?? 0);
+ if (filter && bytesOnDisk > 0) {
+ parts.push(
+ `(filter ${JSON.stringify(filter)} matched no lines β€” call again without \`filter\` to see the raw output)`,
+ );
+ } else if (running) {
+ parts.push('(no output yet)');
+ } else if (exitCode !== undefined || signal) {
+ parts.push('(no output)');
+ }
+ }
+
return parts.join('\n\n');
};
diff --git a/packages/prompts/src/prompts/fileSystem/formatCommandResult.test.ts b/packages/prompts/src/prompts/fileSystem/formatCommandResult.test.ts
index a0ef9e9915c..373ec254c95 100644
--- a/packages/prompts/src/prompts/fileSystem/formatCommandResult.test.ts
+++ b/packages/prompts/src/prompts/fileSystem/formatCommandResult.test.ts
@@ -195,4 +195,38 @@ describe('formatCommandResult', () => {
Some output"
`);
});
+ // `exitCode === undefined` used to be read as "still running"; a signal-killed
+ // command exits without one, so `runCommand` described a killed command as
+ // still going.
+ it('should name the signal rather than claim the command is still running', () => {
+ const result = formatCommandResult({
+ exitCode: undefined,
+ running: false,
+ shellId: 'sh-12',
+ signal: 'SIGKILL',
+ stdout: 'partial work\n',
+ success: true,
+ });
+
+ expect(result).toMatchInlineSnapshot(`
+ "Command was terminated by SIGKILL
+
+ Stdout:
+ partial work
+ "
+ `);
+ expect(result).not.toContain('still running');
+ });
+
+ it('should trust a reported liveness over the exit code', () => {
+ const result = formatCommandResult({
+ exitCode: undefined,
+ running: true,
+ shellId: 'sh-13',
+ success: true,
+ });
+
+ expect(result).toContain('Command is still running after the wait window.');
+ expect(result).not.toContain('(no output)');
+ });
});
diff --git a/packages/prompts/src/prompts/fileSystem/formatCommandResult.ts b/packages/prompts/src/prompts/fileSystem/formatCommandResult.ts
index 0b413767268..2e500fb244b 100644
--- a/packages/prompts/src/prompts/fileSystem/formatCommandResult.ts
+++ b/packages/prompts/src/prompts/fileSystem/formatCommandResult.ts
@@ -7,7 +7,15 @@ export interface FormatCommandResultParams {
stderr?: { path: string; size?: number; truncated?: boolean };
stdout?: { path: string; size?: number; truncated?: boolean };
};
+ /**
+ * Whether the command was still executing when the wait window closed. The
+ * authoritative signal; `exitCode === undefined` is only a fallback for
+ * backends that do not report it.
+ */
+ running?: boolean;
shellId?: string;
+ /** The signal that terminated the command, when one did. */
+ signal?: string;
stderr?: string;
stdout?: string;
success: boolean;
@@ -15,8 +23,10 @@ export interface FormatCommandResultParams {
export const formatCommandResult = ({
success,
+ running,
shellId,
error,
+ signal,
stdout,
stderr,
outputFiles,
@@ -29,14 +39,20 @@ export const formatCommandResult = ({
// so we never render "Command completed successfully." over a 137/130/etc.
const hasNonZeroExit = exitCode !== undefined && exitCode !== 0;
const failed = !success || hasNonZeroExit;
+ // A missing `exitCode` does not by itself mean "still going": a command
+ // killed by a signal exits without one. Trust the backend's own liveness when
+ // it reports it, and name the signal when it does not.
+ const stillRunning = running ?? (exitCode === undefined && !signal);
if (failed) {
let header = 'Command failed';
if (hasNonZeroExit) header += ` with exit code ${exitCode}`;
if (error) header += `: ${error}`;
parts.push(header);
- } else if (exitCode === undefined) {
+ } else if (stillRunning) {
parts.push(`Command is still running after the wait window.\nshell_id: ${shellId}`);
+ } else if (exitCode === undefined && signal) {
+ parts.push(`Command was terminated by ${signal}`);
} else {
parts.push('Command completed successfully.');
}
@@ -63,11 +79,11 @@ export const formatCommandResult = ({
// A command that ran but wrote nothing to either stream has to say so. Without
// the marker, "wrote nothing" and "wrote to stderr, which `2>/dev/null` threw
// away" render as the same lone header line, and the caller reads that silence
- // as a clean run. Only for a command that actually finished β€” `exitCode`
- // undefined is the still-running branch, where empty output means nothing yet.
+ // as a clean run. Only for a command that actually finished β€” while it runs,
+ // empty output means nothing yet.
const hasOutput =
!!stdout || !!stderr || !!outputFiles?.stdout?.path || !!outputFiles?.stderr?.path;
- if (!hasOutput && exitCode !== undefined) parts.push('(no output)');
+ if (!hasOutput && !stillRunning) parts.push('(no output)');
return parts.join('\n\n');
};
diff --git a/packages/tool-runtime/src/ComputerRuntime.ts b/packages/tool-runtime/src/ComputerRuntime.ts
index e7225a69595..a209af66b08 100644
--- a/packages/tool-runtime/src/ComputerRuntime.ts
+++ b/packages/tool-runtime/src/ComputerRuntime.ts
@@ -54,6 +54,14 @@ const MAX_AGENT_GLOB_RESULTS = 1000;
* - Building consistent state objects for UI rendering
*/
export abstract class ComputerRuntime {
+ /**
+ * Whether this backend's `getCommandOutput` manifest exposes a `timeout`, so
+ * a still-running observation may tell the reader to wait longer in one call
+ * rather than poll. Opt-in: the advice is only useful where the schema the
+ * model is holding actually carries the parameter.
+ */
+ protected readonly supportsObservationTimeout: boolean = false;
+
/**
* Call the underlying service to execute a tool.
* Each subclass maps this to its own transport (IPC, HTTP, tRPC, etc.).
@@ -369,7 +377,9 @@ export abstract class ComputerRuntime {
error: r.error,
exitCode: r.exitCode ?? r.exit_code,
outputFiles,
+ running: r.running,
shellId: r.commandId || r.shell_id,
+ signal: r.signal,
stderr: r.stderr,
stdout: r.stdout || r.output,
success: commandSuccess,
@@ -411,25 +421,39 @@ export abstract class ComputerRuntime {
const r = result.result || {};
const outputSuccess = typeof r.success === 'boolean' ? r.success : result.success;
const outputFiles = r.outputFiles ?? r.output_files;
+ const exitCode = r.exitCode ?? r.exit_code;
+ // Liveness comes from the backend. The fallback is for backends that do
+ // not report it and is knowingly lossy β€” a missing `exitCode` also
+ // describes a signalled or never-spawned command β€” so it stays a last
+ // resort. `r.running ?? false` was worse: it hard-coded "not running" for
+ // every such backend, so no consumer could tell a live session from a
+ // finished one.
+ const running = typeof r.running === 'boolean' ? r.running : exitCode === undefined;
const state: GetCommandOutputState = {
...sessionState,
durationMs: r.durationMs ?? r.duration_ms,
error: r.error,
- exitCode: r.exitCode ?? r.exit_code,
+ exitCode,
outputFiles,
- running: r.running ?? false,
+ running,
+ signal: r.signal,
stderr: r.stderr,
stdout: r.stdout,
success: outputSuccess,
};
const content = formatCommandOutput({
+ canWaitLonger: this.supportsObservationTimeout,
durationMs: r.durationMs ?? r.duration_ms,
error: r.error,
- exitCode: r.exitCode ?? r.exit_code,
+ exitCode,
+ filter: args.filter,
output: r.newOutput || r.output,
outputFiles,
+ running,
+ shellId: args.commandId,
+ signal: r.signal,
stderr: r.stderr,
stdout: r.stdout,
success: outputSuccess,
diff --git a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
index fe8c1c3f0f9..475700f6c56 100644
--- a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
+++ b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
@@ -101,6 +101,9 @@ export interface ExecuteLocalToolOptions {
* into the camelCase format expected by ComputerRuntime.
*/
export class LocalSystemExecutionRuntime extends ComputerRuntime {
+ /** `lobe-local-system`'s `getCommandOutput` takes a `timeout`; see its manifest. */
+ protected readonly supportsObservationTimeout = true;
+
private service: ILocalSystemService;
constructor(service: ILocalSystemService) {
@@ -430,6 +433,12 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {
// The picker's chip only shows the user's intent, and a run that
// lost the flag somewhere in between looks identical otherwise.
sandboxed: raw.sandboxed,
+ // Liveness and the terminating signal: `exit_code` alone cannot
+ // tell a running command from a killed one (see
+ // `GetCommandOutputResult`), and dropping them here is what forced
+ // the consumer to guess.
+ running: raw.running,
+ signal: raw.signal,
stderr: raw.stderr,
stdout: raw.stdout,
success: raw.success,
@@ -445,6 +454,8 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {
exitCode: raw.exit_code,
error: raw.error,
outputFiles: raw.output_files,
+ running: raw.running,
+ signal: raw.signal,
stderr: raw.stderr,
stdout: raw.stdout,
success: raw.success,
diff --git a/packages/tool-runtime/src/types.ts b/packages/tool-runtime/src/types.ts
index 3d2ab525a05..15aa99bf1ca 100644
--- a/packages/tool-runtime/src/types.ts
+++ b/packages/tool-runtime/src/types.ts
@@ -298,6 +298,8 @@ export interface GetCommandOutputState {
running?: boolean;
/** The sandbox workspace was recreated before polling this command. */
sessionExpiredAndRecreated?: boolean;
+ /** The signal that terminated the command, when one did. */
+ signal?: string;
stderr?: string;
stdout?: string;
success: boolean;
diff --git a/packages/types/src/agentOperation.ts b/packages/types/src/agentOperation.ts
index 2ac693f326e..b62f8dc3c59 100644
--- a/packages/types/src/agentOperation.ts
+++ b/packages/types/src/agentOperation.ts
@@ -15,5 +15,7 @@ export type AgentOperationCompletionReason =
| 'interrupted'
| 'lease_expired'
| 'max_steps'
+ /** The same tool call was requested over and over; a guard cut the run short. */
+ | 'tool_call_repeat_limit'
| 'waiting_for_async_tool'
| 'waiting_for_human';