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.

:recycle: refactor: + run command observation timeout (#15195)

Rylan Cai3e0a396968a0
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index c8e30535516..4aab6f3740a 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -248,14 +248,14 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
// Handle tool call requests
client.on('tool_call_request', async (request: ToolCallRequestMessage) => {
- const { requestId, toolCall } = request;
+ const { requestId, timeout, toolCall } = request;
if (isDaemonChild) {
appendLog(`[TOOL] ${toolCall.apiName} (${requestId})`);
} else {
log.toolCall(toolCall.apiName, requestId, toolCall.arguments);
}
- const result = await executeToolCall(toolCall.apiName, toolCall.arguments);
+ const result = await executeToolCall(toolCall.apiName, toolCall.arguments, timeout);
if (isDaemonChild) {
appendLog(`[RESULT] ${result.success ? 'OK' : 'FAIL'} (${requestId})`);
diff --git a/apps/cli/src/tools/index.ts b/apps/cli/src/tools/index.ts
index 9851e5cfffd..e6ebbf43999 100644
--- a/apps/cli/src/tools/index.ts
+++ b/apps/cli/src/tools/index.ts
@@ -41,6 +41,7 @@ const methodMap: Record<string, (args: any) => Promise<unknown>> = {
export async function executeToolCall(
apiName: string,
argsStr: string,
+ timeout?: number,
): Promise<{
content: string;
error?: string;
@@ -53,8 +54,12 @@ export async function executeToolCall(
try {
const args = JSON.parse(argsStr);
+ const finalArgs =
+ typeof timeout === 'number' && Number.isFinite(timeout) && !('timeout' in args)
+ ? { ...args, timeout }
+ : args;
- const result = await handler(args);
+ const result = await handler(finalArgs);
const content = typeof result === 'string' ? result : JSON.stringify(result);
return { content, success: true };
diff --git a/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
index 92b9754b22d..91c36d0fb8c 100644
--- a/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
@@ -29,10 +29,6 @@ vi.mock('node:child_process', () => ({
spawn: vi.fn(),
}));
-vi.mock('node:crypto', () => ({
- randomUUID: vi.fn(() => 'test-uuid-123'),
-}));
-
vi.mock('../CliCtr', () => ({
default: class CliCtr {},
}));
@@ -59,7 +55,9 @@ describe('ShellCommandCtr (thin wrapper)', () => {
mockChildProcess = {
stdout: { on: vi.fn() },
stderr: { on: vi.fn() },
+ off: vi.fn(),
on: vi.fn(),
+ once: vi.fn(),
kill: vi.fn(),
exitCode: null,
};
@@ -73,6 +71,10 @@ describe('ShellCommandCtr (thin wrapper)', () => {
if (event === 'exit') setTimeout(() => callback(0), 10);
return mockChildProcess;
});
+ mockChildProcess.once.mockImplementation((event: string, callback: any) => {
+ if (event === 'exit') setTimeout(() => callback(0), 10);
+ return mockChildProcess;
+ });
mockChildProcess.stdout.on.mockImplementation((event: string, callback: any) => {
if (event === 'data') setTimeout(() => callback(Buffer.from('output\n')), 5);
return mockChildProcess.stdout;
@@ -89,14 +91,21 @@ describe('ShellCommandCtr (thin wrapper)', () => {
});
it('should delegate handleGetCommandOutput to processManager', async () => {
- mockChildProcess.on.mockImplementation(() => mockChildProcess);
+ mockChildProcess.on.mockImplementation((event: string, callback: any) => {
+ if (event === 'exit') setTimeout(() => callback(0), 10);
+ return mockChildProcess;
+ });
+ mockChildProcess.once.mockImplementation((event: string, callback: any) => {
+ if (event === 'exit') setTimeout(() => callback(0), 10);
+ return mockChildProcess;
+ });
mockChildProcess.stdout.on.mockImplementation((event: string, callback: any) => {
if (event === 'data') setTimeout(() => callback(Buffer.from('bg output\n')), 5);
return mockChildProcess.stdout;
});
mockChildProcess.stderr.on.mockImplementation(() => mockChildProcess.stderr);
- await ctr.handleRunCommand({
+ const runResult = await ctr.handleRunCommand({
command: 'test',
run_in_background: true,
});
@@ -104,7 +113,7 @@ describe('ShellCommandCtr (thin wrapper)', () => {
await new Promise((r) => setTimeout(r, 20));
const result = await ctr.handleGetCommandOutput({
- shell_id: 'test-uuid-123',
+ shell_id: runResult.shell_id!,
});
expect(result.success).toBe(true);
@@ -113,16 +122,17 @@ describe('ShellCommandCtr (thin wrapper)', () => {
it('should delegate handleKillCommand to processManager', async () => {
mockChildProcess.on.mockImplementation(() => mockChildProcess);
+ mockChildProcess.once.mockImplementation(() => mockChildProcess);
mockChildProcess.stdout.on.mockImplementation(() => mockChildProcess.stdout);
mockChildProcess.stderr.on.mockImplementation(() => mockChildProcess.stderr);
- await ctr.handleRunCommand({
+ const runResult = await ctr.handleRunCommand({
command: 'test',
run_in_background: true,
});
const result = await ctr.handleKillCommand({
- shell_id: 'test-uuid-123',
+ shell_id: runResult.shell_id!,
});
expect(result.success).toBe(true);
diff --git a/packages/builtin-tool-local-system/src/ExecutionRuntime/index.ts b/packages/builtin-tool-local-system/src/ExecutionRuntime/index.ts
index e5a07485a59..68e8db1c308 100644
--- a/packages/builtin-tool-local-system/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-local-system/src/ExecutionRuntime/index.ts
@@ -185,9 +185,9 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {
case 'getCommandOutput': {
return {
result: {
+ exitCode: raw.exit_code,
error: raw.error,
newOutput: raw.output,
- running: raw.running,
success: raw.success,
},
success: raw.success,
diff --git a/packages/builtin-tool-local-system/src/__tests__/grepContentForwarding.test.ts b/packages/builtin-tool-local-system/src/__tests__/grepContentForwarding.test.ts
index ad3845e917a..71772e3a5f8 100644
--- a/packages/builtin-tool-local-system/src/__tests__/grepContentForwarding.test.ts
+++ b/packages/builtin-tool-local-system/src/__tests__/grepContentForwarding.test.ts
@@ -148,7 +148,7 @@ describe('localSystemExecutor.getCommandOutput β€” filter forwarding', () => {
};
const spy = vi.spyOn(runtime, 'getCommandOutput').mockResolvedValue({
content: '',
- state: { newOutput: '', running: false, success: true },
+ state: { exitCode: 0, newOutput: '', success: true },
success: true,
});
@@ -161,6 +161,33 @@ describe('localSystemExecutor.getCommandOutput β€” filter forwarding', () => {
spy.mockRestore();
});
+
+ it('preserves `exitCode` state from getCommandOutput', async () => {
+ const runtime = (localSystemExecutor as any).runtime as {
+ getCommandOutput: (args: any) => Promise<unknown>;
+ };
+ const spy = vi.spyOn(runtime, 'getCommandOutput');
+
+ spy.mockResolvedValueOnce({
+ content: '',
+ state: { exitCode: undefined, newOutput: '', success: true },
+ success: true,
+ });
+
+ const runningResult = await localSystemExecutor.getCommandOutput({ shell_id: 'sh-running' });
+ expect(runningResult.state).toMatchObject({ exitCode: undefined });
+
+ spy.mockResolvedValueOnce({
+ content: '',
+ state: { exitCode: 0, newOutput: 'done', success: true },
+ success: true,
+ });
+
+ const doneResult = await localSystemExecutor.getCommandOutput({ shell_id: 'sh-done' });
+ expect(doneResult.state).toMatchObject({ exitCode: 0 });
+
+ spy.mockRestore();
+ });
});
describe('localSystemExecutor.runCommand β€” background field normalization', () => {
diff --git a/packages/builtin-tool-local-system/src/manifest.ts b/packages/builtin-tool-local-system/src/manifest.ts
index b69ec38e435..f1d4b33e5d2 100644
--- a/packages/builtin-tool-local-system/src/manifest.ts
+++ b/packages/builtin-tool-local-system/src/manifest.ts
@@ -263,9 +263,9 @@ export const LocalSystemManifest: BuiltinToolManifest = {
},
},
{
- defaultTimeoutMs: 120_000,
+ defaultTimeoutMs: 30_000,
description:
- 'Execute a shell command and return its output. Supports both synchronous and background execution with timeout control.',
+ 'Start a terminal session to execute a shell command and return console output collected during the wait window. If the command exits during that window, the result includes `exit_code`; if it is still running, the result includes `shell_id` for later output retrieval or termination.',
humanIntervention: 'required',
name: LocalSystemApiName.runCommand,
parameters: {
@@ -286,13 +286,9 @@ export const LocalSystemManifest: BuiltinToolManifest = {
type: 'object',
},
run_in_background: {
- description: 'Set to true to run command in background and return shell_id',
- type: 'boolean',
- },
- timeout: {
description:
- 'Timeout in milliseconds for this command. Default 120000ms. Server clamps to [1000, 800000]; raise this for long-running tasks (builds, large searches) instead of letting them hit the default and fail.',
- type: 'number',
+ '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',
},
},
required: ['description', 'command'],
diff --git a/packages/builtin-tool-local-system/src/systemRole.desktop.ts b/packages/builtin-tool-local-system/src/systemRole.desktop.ts
index 9e4d3bb3f09..5b29dc7f5ac 100644
--- a/packages/builtin-tool-local-system/src/systemRole.desktop.ts
+++ b/packages/builtin-tool-local-system/src/systemRole.desktop.ts
@@ -28,9 +28,9 @@ You have access to a set of tools to interact with the user's local file system:
5. **moveFiles**: Moves multiple files or directories. Also handles renames β€” pass the original directory with the new filename in \`newPath\`.
**Shell Commands:**
-6. **runCommand**: Execute shell commands with timeout control. Supports both synchronous and background execution. When providing a description, always use the same language as the user's input.
-7. **getCommandOutput**: Retrieve output from running background commands. Returns only new output since last check.
-8. **killCommand**: Terminate a running background shell command by its ID.
+6. **runCommand**: Start a terminal session to execute shell commands and return console output collected during the wait window. When providing a description, always use the same language as the user's input.
+7. **getCommandOutput**: Retrieve output from an existing terminal session. Returns only new output since last check.
+8. **killCommand**: Terminate a running terminal session by its ID.
**Search & Find:**
9. **searchFiles**: Searches for files based on keywords and other criteria using native search. Use this tool to find files if the user is unsure about the exact path.
@@ -85,14 +85,17 @@ You have access to a set of tools to interact with the user's local file system:
- For executing shell commands: Use 'runCommand'. Provide the following parameters:
- '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 run in background and get a shell_id for later checking output.
- - 'timeout' (Optional): Timeout in milliseconds (default: 120000ms, max: 800000ms).
+ - '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.
The command runs in cmd.exe on Windows or /bin/sh on macOS/Linux.
-- For retrieving output from background commands: Use 'getCommandOutput'. Provide:
- - 'shell_id': The ID returned from runCommand when run_in_background was true.
+ - Result semantics:
+ - 'success' indicates whether the tool call itself succeeded.
+ - 'shell_id' identifies the terminal session for later observation/termination.
+ - 'exit_code' is only present after the command has exited. If it is absent, the command is still running.
+- 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 only new output since the last check.
-- For killing background commands: Use 'killCommand' with 'shell_id'.
+- For killing running terminal sessions: Use 'killCommand' with 'shell_id'.
- For searching content in files: Use 'grepContent'. Provide:
- 'pattern': The regex pattern to search for.
- 'scope' (Optional): Directory to search in. Defaults to the working directory if omitted.
@@ -118,7 +121,6 @@ You have access to a set of tools to interact with the user's local file system:
- Be cautious with commands that have side effects (e.g., rm, sudo, format).
- Always describe what a command will do before running it, especially for non-trivial operations.
- Always provide a clear 'description' parameter in the user's language to help them understand what the command does.
- - Use appropriate timeouts to prevent commands from running indefinitely.
- When editing files:
- Always read the file first to verify its current content.
- Ensure old_string exactly matches the text to be replaced to avoid unintended changes.
diff --git a/packages/builtin-tool-local-system/src/systemRole.ts b/packages/builtin-tool-local-system/src/systemRole.ts
index 79e1ef3cee7..9ec60c36017 100644
--- a/packages/builtin-tool-local-system/src/systemRole.ts
+++ b/packages/builtin-tool-local-system/src/systemRole.ts
@@ -17,9 +17,9 @@ You have access to a set of tools to interact with the user's local file system:
5. **moveFiles**: Moves multiple files or directories. Also handles renames β€” pass the original directory with the new filename in \`newPath\`.
**Shell Commands:**
-6. **runCommand**: Execute shell commands with timeout control. Supports both synchronous and background execution. When providing a description, always use the same language as the user's input.
-7. **getCommandOutput**: Retrieve output from running background commands. Returns only new output since last check.
-8. **killCommand**: Terminate a running background shell command by its ID.
+6. **runCommand**: Start a terminal session to execute shell commands and return console output collected during the wait window. When providing a description, always use the same language as the user's input.
+7. **getCommandOutput**: Retrieve output from an existing terminal session. Returns only new output since last check.
+8. **killCommand**: Terminate a running terminal session by its ID.
**Search & Find:**
9. **searchFiles**: Searches for files based on keywords and other criteria using native search. Use this tool to find files if the user is unsure about the exact path.
@@ -74,14 +74,17 @@ You have access to a set of tools to interact with the user's local file system:
- For executing shell commands: Use 'runCommand'. Provide the following parameters:
- '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 run in background and get a shell_id for later checking output.
- - 'timeout' (Optional): Timeout in milliseconds (default: 120000ms, max: 800000ms).
+ - '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.
The command runs in cmd.exe on Windows or /bin/sh on macOS/Linux.
-- For retrieving output from background commands: Use 'getCommandOutput'. Provide:
- - 'shell_id': The ID returned from runCommand when run_in_background was true.
+ - Result semantics:
+ - 'success' indicates whether the tool call itself succeeded.
+ - 'shell_id' identifies the terminal session for later observation/termination.
+ - 'exit_code' is only present after the command has exited. If it is absent, the command is still running.
+- 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 only new output since the last check.
-- For killing background commands: Use 'killCommand' with 'shell_id'.
+- For killing running terminal sessions: Use 'killCommand' with 'shell_id'.
- For searching content in files: Use 'grepContent'. Provide:
- 'pattern': The regex pattern to search for.
- 'scope' (Optional): Directory to search in. Defaults to the working directory if omitted.
diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.ts
index 39b6d61aacc..6e8c2d64df6 100644
--- a/packages/device-gateway-client/src/http.test.ts
+++ b/packages/device-gateway-client/src/http.test.ts
@@ -221,19 +221,43 @@ describe('GatewayHttpClient', () => {
json: vi.fn().mockResolvedValue({ content: 'ok', success: true }),
ok: true,
});
+ const signal = AbortSignal.abort();
+ const timeoutSpy = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(signal);
await client.executeToolCall(
{ deviceId: 'device-1', timeout: 5000, userId: 'user-1' },
{ apiName: 'readFile', arguments: '{}', identifier: 'test' },
);
+ expect(timeoutSpy).toHaveBeenCalledWith(35_000);
expect(fetch).toHaveBeenCalledWith(
'https://gateway.test.com/api/device/tool-call',
expect.objectContaining({
body: expect.stringContaining('"deviceId":"device-1"'),
+ signal,
}),
);
});
+
+ it('should use default gateway timeout plus HTTP caller padding when timeout is absent', async () => {
+ mockFetch({
+ json: vi.fn().mockResolvedValue({ content: 'ok', success: true }),
+ ok: true,
+ });
+ const signal = AbortSignal.abort();
+ const timeoutSpy = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(signal);
+
+ await client.executeToolCall(
+ { userId: 'user-1' },
+ { apiName: 'readFile', arguments: '{}', identifier: 'test' },
+ );
+
+ expect(timeoutSpy).toHaveBeenCalledWith(60_000);
+ expect(fetch).toHaveBeenCalledWith(
+ 'https://gateway.test.com/api/device/tool-call',
+ expect.objectContaining({ signal }),
+ );
+ });
});
describe('getDeviceSystemInfo', () => {
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index 805641dda8c..c15175d920b 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -1,5 +1,8 @@
import type { DeviceAttachment, DeviceSystemInfo } from './types';
+const DEFAULT_GATEWAY_TOOL_CALL_TIMEOUT_MS = 30_000;
+const HTTP_CALL_TIMEOUT_PADDING_MS = 30_000;
+
export interface DeviceStatusResult {
deviceCount: number;
online: boolean;
@@ -48,12 +51,20 @@ export class GatewayHttpClient {
params: { deviceId?: string; timeout?: number; userId: string },
toolCall: { apiName: string; arguments: string; identifier: string },
): Promise<DeviceToolCallResult> {
- const res = await this.post('/api/device/tool-call', {
- deviceId: params.deviceId,
- timeout: params.timeout,
- toolCall,
- userId: params.userId,
- });
+ const timeout =
+ typeof params.timeout === 'number' && Number.isFinite(params.timeout)
+ ? Math.max(Math.trunc(params.timeout), 0)
+ : DEFAULT_GATEWAY_TOOL_CALL_TIMEOUT_MS;
+ const res = await this.post(
+ '/api/device/tool-call',
+ {
+ deviceId: params.deviceId,
+ timeout: params.timeout,
+ toolCall,
+ userId: params.userId,
+ },
+ { timeout: timeout + HTTP_CALL_TIMEOUT_PADDING_MS },
+ );
if (!res.ok) {
const text = await res.text().catch(() => '');
@@ -109,7 +120,7 @@ export class GatewayHttpClient {
};
}
- private post(path: string, body: unknown): Promise<Response> {
+ private post(path: string, body: unknown, options?: { timeout?: number }): Promise<Response> {
return fetch(`${this.gatewayUrl}${path}`, {
body: JSON.stringify(body),
headers: {
@@ -117,6 +128,7 @@ export class GatewayHttpClient {
'Content-Type': 'application/json',
},
method: 'POST',
+ ...(options?.timeout ? { signal: AbortSignal.timeout(options.timeout) } : {}),
});
}
}
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index 62a0cf6eb52..27b0aca6a93 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -234,12 +234,22 @@ export interface RunCommandResult {
export interface GetCommandOutputParams {
filter?: string;
shell_id: string;
+ /**
+ * Maximum time to wait for this observation before returning.
+ * Does not kill the process when the timeout elapses.
+ */
+ timeout?: number;
}
export interface GetCommandOutputResult {
error?: string;
+ /**
+ * Present only after the command has exited.
+ * `0` means success, non-zero means the command finished with an error.
+ * `undefined` means the command is still running.
+ */
+ exit_code?: number;
output: string;
- running: boolean;
stderr: string;
stdout: string;
success: boolean;
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 c159ec96d30..490acffc889 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
@@ -1,14 +1,32 @@
import type { ChildProcess } from 'node:child_process';
+import { EventEmitter } from 'node:events';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { ShellProcessManager } from '../process-manager';
+import { type ShellProcess, ShellProcessManager } from '../process-manager';
function createMockProcess(exitCode: number | null = null): ChildProcess {
+ const process = new EventEmitter() as ChildProcess;
+ // Node types expose `exitCode` as readonly; make the test double writable so
+ // we can simulate the child process exiting.
+ Object.defineProperty(process, 'exitCode', {
+ configurable: true,
+ value: exitCode,
+ writable: true,
+ });
+ process.kill = vi.fn() as unknown as ChildProcess['kill'];
+ return process;
+}
+
+function createShellProcess(process: ChildProcess): ShellProcess {
return {
- exitCode,
- kill: vi.fn(),
- } as unknown as ChildProcess;
+ exitCode: process.exitCode,
+ lastReadStderr: 0,
+ lastReadStdout: 0,
+ process,
+ stderr: [],
+ stdout: [],
+ };
}
describe('ShellProcessManager', () => {
@@ -19,143 +37,179 @@ describe('ShellProcessManager', () => {
});
describe('getOutput', () => {
- it('should return error for non-existent shell_id', () => {
- const result = manager.getOutput({ shell_id: 'non-existent' });
+ it('should return error for non-existent shell_id', async () => {
+ const result = await manager.getOutput({ shell_id: 'non-existent' });
expect(result.success).toBe(false);
expect(result.error).toContain('not found');
- expect(result.running).toBe(false);
});
- it('should retrieve stdout and stderr', () => {
+ it('should retrieve stdout and stderr', async () => {
const process = createMockProcess();
manager.register('test-1', {
- lastReadStderr: 0,
- lastReadStdout: 0,
- process,
+ ...createShellProcess(process),
stderr: ['error line\n'],
stdout: ['line 1\n', 'line 2\n'],
});
- const result = manager.getOutput({ shell_id: 'test-1' });
+ const result = await manager.getOutput({ shell_id: 'test-1', timeout: 0 });
expect(result.success).toBe(true);
expect(result.stdout).toContain('line 1');
expect(result.stdout).toContain('line 2');
expect(result.stderr).toContain('error line');
+ expect(result.exit_code).toBeUndefined();
});
- it('should only return new output since last read', () => {
+ it('should return only new buffered output on repeated reads', async () => {
const process = createMockProcess();
const shellProcess = {
- lastReadStderr: 0,
- lastReadStdout: 0,
- process,
- stderr: [] as string[],
+ ...createShellProcess(process),
stdout: ['first\n'],
};
manager.register('test-1', shellProcess);
- const first = manager.getOutput({ shell_id: 'test-1' });
+ const first = await manager.getOutput({ shell_id: 'test-1', timeout: 0 });
expect(first.stdout).toContain('first');
- // No new output
- const second = manager.getOutput({ shell_id: 'test-1' });
+ const second = await manager.getOutput({ shell_id: 'test-1', timeout: 0 });
expect(second.stdout).toBe('');
- expect(second.stderr).toBe('');
- // Add new output
shellProcess.stdout.push('second\n');
- const third = manager.getOutput({ shell_id: 'test-1' });
- expect(third.stdout).toContain('second');
- expect(third.stdout).not.toContain('first');
+ const third = await manager.getOutput({ shell_id: 'test-1', timeout: 0 });
+ expect(third.stdout).toBe('second\n');
});
- it('should track stdout and stderr offsets separately', () => {
+ it('should return the current output snapshot when observation timeout elapses', async () => {
+ vi.useFakeTimers();
+ try {
+ const process = createMockProcess();
+ const shellProcess = createShellProcess(process);
+ manager.register('test-1', shellProcess);
+ let resolved = false;
+
+ const pending = manager.getOutput({ shell_id: 'test-1', timeout: 100 }).then((result) => {
+ resolved = true;
+ return result;
+ });
+
+ setTimeout(() => {
+ shellProcess.stdout.push('delayed\n');
+ }, 20);
+
+ await vi.advanceTimersByTimeAsync(20);
+ expect(resolved).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(80);
+ const result = await pending;
+ expect(result.stdout).toContain('delayed');
+ expect(result.exit_code).toBeUndefined();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('should wait up to the default observation timeout when timeout is omitted', async () => {
+ vi.useFakeTimers();
+ try {
+ const process = createMockProcess();
+ const shellProcess = createShellProcess(process);
+ manager.register('test-1', shellProcess);
+ let resolved = false;
+
+ const pending = manager.getOutput({ shell_id: 'test-1' }).then((result) => {
+ resolved = true;
+ return result;
+ });
+
+ await vi.advanceTimersByTimeAsync(29_999);
+ expect(resolved).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(1);
+ const result = await pending;
+ expect(result.success).toBe(true);
+ expect(result.exit_code).toBeUndefined();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('should return done when process exits before new output', async () => {
const process = createMockProcess();
- const shellProcess = {
- lastReadStderr: 0,
- lastReadStdout: 0,
- process,
- stderr: [] as string[],
- stdout: [] as string[],
- };
- manager.register('test-1', shellProcess);
+ manager.register('test-1', createShellProcess(process));
- // Add stderr only
- shellProcess.stderr.push('error 1\n');
- const read1 = manager.getOutput({ shell_id: 'test-1' });
- expect(read1.stderr).toBe('error 1\n');
- expect(read1.stdout).toBe('');
+ const pending = manager.getOutput({ shell_id: 'test-1', timeout: 100 });
- // Add stdout only
- shellProcess.stdout.push('output 1\n');
- const read2 = manager.getOutput({ shell_id: 'test-1' });
- expect(read2.stdout).toBe('output 1\n');
- expect(read2.stderr).toBe('');
+ setTimeout(() => {
+ (process as { exitCode: number | null }).exitCode = 0;
+ process.emit('exit', 0);
+ }, 20);
+
+ const result = await pending;
+ expect(result.exit_code).toBe(0);
});
- it('should filter output with regex', () => {
+ it('should filter output with regex', async () => {
const process = createMockProcess();
manager.register('test-1', {
- lastReadStderr: 0,
- lastReadStdout: 0,
- process,
- stderr: [],
- stdout: ['line 1\n', 'line 2\n', 'line 3\n'],
+ ...createShellProcess(process),
+ stdout: ['line 1\nline 2\nline 3\n'],
});
- const result = manager.getOutput({ filter: 'line 1', shell_id: 'test-1' });
+ const result = await manager.getOutput({ filter: 'line 1', shell_id: 'test-1', timeout: 0 });
expect(result.success).toBe(true);
expect(result.output).toContain('line 1');
expect(result.output).not.toContain('line 2');
});
- it('should handle invalid regex filter gracefully', () => {
+ it('should handle invalid regex filter gracefully', async () => {
const process = createMockProcess();
- manager.register('test-1', {
- lastReadStderr: 0,
- lastReadStdout: 0,
- process,
- stderr: [],
- stdout: ['output\n'],
- });
+ manager.register('test-1', { ...createShellProcess(process), stdout: ['output\n'] });
- const result = manager.getOutput({ filter: '[invalid(regex', shell_id: 'test-1' });
+ const result = await manager.getOutput({
+ filter: '[invalid(regex',
+ shell_id: 'test-1',
+ timeout: 0,
+ });
expect(result.success).toBe(true);
- // Should return unfiltered output
+ expect(result.output).toContain('output');
+ });
+
+ it('should reflect completion via exit_code', async () => {
+ const process = createMockProcess();
+ manager.register('test-1', createShellProcess(process));
+
+ let result = await manager.getOutput({ shell_id: 'test-1', timeout: 0 });
+ expect(result.exit_code).toBeUndefined();
+
+ (process as { exitCode: number | null }).exitCode = 0;
+
+ result = await manager.getOutput({ shell_id: 'test-1', timeout: 0 });
+ expect(result.exit_code).toBe(0);
});
- it('should report running status correctly', () => {
- const runningProcess = createMockProcess(null);
+ it('should retain completed output after the process exits', async () => {
+ const process = createMockProcess();
manager.register('test-1', {
- lastReadStderr: 0,
- lastReadStdout: 0,
- process: runningProcess,
- stderr: [],
- stdout: [],
+ ...createShellProcess(process),
+ stdout: ['done\n'],
});
- expect(manager.getOutput({ shell_id: 'test-1' }).running).toBe(true);
+ (process as { exitCode: number | null }).exitCode = 0;
- // Simulate exit
- (runningProcess as any).exitCode = 0;
- expect(manager.getOutput({ shell_id: 'test-1' }).running).toBe(false);
+ const result = await manager.getOutput({ shell_id: 'test-1', timeout: 0 });
+ expect(result.success).toBe(true);
+ expect(result.exit_code).toBe(0);
+ expect(result.stdout).toContain('done');
});
});
describe('kill', () => {
it('should kill process successfully', () => {
const process = createMockProcess();
- manager.register('test-1', {
- lastReadStderr: 0,
- lastReadStdout: 0,
- process,
- stderr: [],
- stdout: [],
- });
+ manager.register('test-1', createShellProcess(process));
const result = manager.kill('test-1');
@@ -170,35 +224,23 @@ describe('ShellProcessManager', () => {
expect(result.error).toContain('not found');
});
- it('should remove process from registry after killing', () => {
+ it('should remove process from registry after killing', async () => {
const process = createMockProcess();
- manager.register('test-1', {
- lastReadStderr: 0,
- lastReadStdout: 0,
- process,
- stderr: [],
- stdout: [],
- });
+ manager.register('test-1', createShellProcess(process));
manager.kill('test-1');
- const result = manager.getOutput({ shell_id: 'test-1' });
+ const result = await manager.getOutput({ shell_id: 'test-1' });
expect(result.success).toBe(false);
expect(result.error).toContain('not found');
});
it('should handle kill error gracefully', () => {
const process = createMockProcess();
- (process.kill as any).mockImplementation(() => {
+ (process.kill as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => {
throw new Error('Kill failed');
});
- manager.register('test-1', {
- lastReadStderr: 0,
- lastReadStdout: 0,
- process,
- stderr: [],
- stdout: [],
- });
+ manager.register('test-1', createShellProcess(process));
const result = manager.kill('test-1');
@@ -208,46 +250,27 @@ describe('ShellProcessManager', () => {
});
describe('cleanupAll', () => {
- it('should kill all registered processes', () => {
+ it('should kill all registered processes', async () => {
const p1 = createMockProcess();
const p2 = createMockProcess();
- manager.register('test-1', {
- lastReadStderr: 0,
- lastReadStdout: 0,
- process: p1,
- stderr: [],
- stdout: [],
- });
- manager.register('test-2', {
- lastReadStderr: 0,
- lastReadStdout: 0,
- process: p2,
- stderr: [],
- stdout: [],
- });
+ manager.register('test-1', createShellProcess(p1));
+ manager.register('test-2', createShellProcess(p2));
manager.cleanupAll();
expect(p1.kill).toHaveBeenCalled();
expect(p2.kill).toHaveBeenCalled();
- expect(manager.getOutput({ shell_id: 'test-1' }).success).toBe(false);
- expect(manager.getOutput({ shell_id: 'test-2' }).success).toBe(false);
+ expect((await manager.getOutput({ shell_id: 'test-1' })).success).toBe(false);
+ expect((await manager.getOutput({ shell_id: 'test-2' })).success).toBe(false);
});
it('should handle kill errors during cleanup', () => {
const p1 = createMockProcess();
- (p1.kill as any).mockImplementation(() => {
+ (p1.kill as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => {
throw new Error('fail');
});
- manager.register('test-1', {
- lastReadStderr: 0,
- lastReadStdout: 0,
- process: p1,
- stderr: [],
- stdout: [],
- });
+ manager.register('test-1', createShellProcess(p1));
- // Should not throw
expect(() => manager.cleanupAll()).not.toThrow();
});
});
diff --git a/packages/local-file-shell/src/shell/__tests__/runner.test.ts b/packages/local-file-shell/src/shell/__tests__/runner.test.ts
index a4dd7c14f33..db193b5c592 100644
--- a/packages/local-file-shell/src/shell/__tests__/runner.test.ts
+++ b/packages/local-file-shell/src/shell/__tests__/runner.test.ts
@@ -10,13 +10,25 @@ describe('runCommand', () => {
processManager.cleanupAll();
});
- describe('synchronous mode', () => {
- it('should execute a simple command', async () => {
+ describe('foreground observation mode', () => {
+ it('should execute a simple command and finish immediately', async () => {
const result = await runCommand({ command: 'echo hello' }, { processManager });
expect(result.success).toBe(true);
expect(result.stdout).toContain('hello');
expect(result.exit_code).toBe(0);
+ expect(result.shell_id).toBeDefined();
+ });
+
+ it('should assign readable incremental shell IDs within a manager', async () => {
+ const localManager = new ShellProcessManager();
+
+ const first = await runCommand({ command: 'echo first' }, { processManager: localManager });
+ const second = await runCommand({ command: 'echo second' }, { processManager: localManager });
+
+ expect(first.shell_id).toBe('sh-1');
+ expect(second.shell_id).toBe('sh-2');
+ localManager.cleanupAll();
});
it('should capture stderr', async () => {
@@ -28,7 +40,7 @@ describe('runCommand', () => {
it('should handle command failure', async () => {
const result = await runCommand({ command: 'exit 1' }, { processManager });
- expect(result.success).toBe(false);
+ expect(result.success).toBe(true);
expect(result.exit_code).toBe(1);
});
@@ -38,15 +50,20 @@ describe('runCommand', () => {
{ processManager },
);
- expect(result.success).toBe(false);
+ expect(result.success).toBe(true);
+ expect(result.exit_code).not.toBe(0);
});
- it('should timeout long-running commands', async () => {
- const result = await runCommand({ command: 'sleep 10', timeout: 500 }, { processManager });
+ it('should return partial observation instead of killing long-running commands', async () => {
+ const result = await runCommand(
+ { command: 'sleep 1 && echo done', timeout: 100 },
+ { processManager },
+ );
- expect(result.success).toBe(false);
- expect(result.error).toContain('timed out');
- }, 10000);
+ expect(result.success).toBe(true);
+ expect(result.exit_code).toBeUndefined();
+ expect(result.shell_id).toBeDefined();
+ }, 10_000);
it('should strip ANSI codes from output', async () => {
const result = await runCommand(
@@ -65,8 +82,8 @@ describe('runCommand', () => {
{ processManager },
);
- expect(result.output!.length).toBeLessThanOrEqual(85000);
- }, 15000);
+ expect(result.output!.length).toBeLessThanOrEqual(85_000);
+ }, 15_000);
it('should pass cwd to command', async () => {
const result = await runCommand({ command: 'pwd', cwd: '/tmp' }, { processManager });
@@ -90,7 +107,7 @@ describe('runCommand', () => {
});
describe('background mode', () => {
- it('should run command in background', async () => {
+ it('should run command in background and return a shell_id', async () => {
const result = await runCommand(
{ command: 'echo background', run_in_background: true },
{ processManager },
@@ -98,6 +115,7 @@ describe('runCommand', () => {
expect(result.success).toBe(true);
expect(result.shell_id).toBeDefined();
+ expect(result.exit_code).toBeUndefined();
});
it('should capture background process output', async () => {
@@ -108,27 +126,25 @@ describe('runCommand', () => {
await new Promise((r) => setTimeout(r, 200));
- const output = processManager.getOutput({ shell_id: bgResult.shell_id! });
+ const output = await processManager.getOutput({ shell_id: bgResult.shell_id! });
expect(output.success).toBe(true);
expect(output.stdout).toContain('hello');
});
- it('should return new output only on subsequent reads', async () => {
+ it('should return only new buffered output on subsequent reads', async () => {
const bgResult = await runCommand(
{ command: 'echo first && sleep 0.2 && echo second', run_in_background: true },
{ processManager },
);
await new Promise((r) => setTimeout(r, 100));
- const first = processManager.getOutput({ shell_id: bgResult.shell_id! });
+ const first = await processManager.getOutput({ shell_id: bgResult.shell_id!, timeout: 0 });
expect(first.stdout).toContain('first');
await new Promise((r) => setTimeout(r, 300));
- processManager.getOutput({ shell_id: bgResult.shell_id! });
-
- // First read should have had "first"
- expect(first.stdout).toContain('first');
+ const second = await processManager.getOutput({ shell_id: bgResult.shell_id!, timeout: 0 });
+ expect(second.stdout).toContain('second');
});
});
@@ -144,7 +160,7 @@ describe('runCommand', () => {
});
it('should return error for unknown shell_id', async () => {
- const result = processManager.getOutput({ shell_id: 'unknown-id' });
+ const result = await processManager.getOutput({ shell_id: 'unknown-id' });
expect(result.success).toBe(false);
expect(result.error).toContain('not found');
});
@@ -163,12 +179,13 @@ describe('runCommand', () => {
await new Promise((r) => setTimeout(r, 200));
- const output = processManager.getOutput({
+ const output = await processManager.getOutput({
filter: 'line2',
shell_id: bgResult.shell_id!,
});
expect(output.success).toBe(true);
+ expect(output.output).toContain('line2');
});
it('should handle invalid filter regex', async () => {
@@ -179,7 +196,7 @@ describe('runCommand', () => {
await new Promise((r) => setTimeout(r, 200));
- const output = processManager.getOutput({
+ const output = await processManager.getOutput({
filter: '[invalid',
shell_id: bgResult.shell_id!,
});
@@ -187,14 +204,15 @@ describe('runCommand', () => {
expect(output.success).toBe(true);
});
- it('should track running state', async () => {
+ it('should track running state after completion', async () => {
const bgResult = await runCommand(
- { command: 'sleep 5', run_in_background: true },
+ { command: 'sleep 0.05', run_in_background: true },
{ processManager },
);
- const output = processManager.getOutput({ shell_id: bgResult.shell_id! });
- expect(output.running).toBe(true);
+ await new Promise((r) => setTimeout(r, 100));
+ const output = await processManager.getOutput({ shell_id: bgResult.shell_id! });
+ expect(output.exit_code).toBe(0);
});
});
diff --git a/packages/local-file-shell/src/shell/process-manager.ts b/packages/local-file-shell/src/shell/process-manager.ts
index 01214f3beb6..5f3bc22217d 100644
--- a/packages/local-file-shell/src/shell/process-manager.ts
+++ b/packages/local-file-shell/src/shell/process-manager.ts
@@ -3,7 +3,11 @@ import type { ChildProcess } from 'node:child_process';
import type { GetCommandOutputParams, GetCommandOutputResult, KillCommandResult } from '../types';
import { truncateOutput } from './utils';
+const DEFAULT_OBSERVATION_TIMEOUT_MS = 30_000;
+const MAX_OBSERVATION_TIMEOUT_MS = 120_000;
+
export interface ShellProcess {
+ exitCode: number | null;
lastReadStderr: number;
lastReadStdout: number;
process: ChildProcess;
@@ -12,19 +16,28 @@ export interface ShellProcess {
}
export class ShellProcessManager {
+ private nextShellId = 1;
+
private processes = new Map<string, ShellProcess>();
+ createShellId(): string {
+ return `sh-${this.nextShellId++}`;
+ }
+
register(shellId: string, shellProcess: ShellProcess): void {
this.processes.set(shellId, shellProcess);
}
- getOutput({ shell_id, filter }: GetCommandOutputParams): GetCommandOutputResult {
+ async getOutput({
+ filter,
+ shell_id,
+ timeout,
+ }: GetCommandOutputParams): Promise<GetCommandOutputResult> {
const shellProcess = this.processes.get(shell_id);
if (!shellProcess) {
return {
error: `Shell ID ${shell_id} not found`,
output: '',
- running: false,
stderr: '',
stdout: '',
success: false,
@@ -33,6 +46,42 @@ export class ShellProcessManager {
const { lastReadStderr, lastReadStdout, process: childProcess, stderr, stdout } = shellProcess;
+ let exitCode = childProcess.exitCode ?? shellProcess.exitCode;
+ if (exitCode === null) {
+ const waitTimeout =
+ typeof timeout === 'number' && Number.isFinite(timeout)
+ ? Math.min(Math.max(Math.trunc(timeout), 0), MAX_OBSERVATION_TIMEOUT_MS)
+ : DEFAULT_OBSERVATION_TIMEOUT_MS;
+
+ if (waitTimeout > 0) {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let onError: (() => void) | undefined;
+ let onExit: (() => void) | undefined;
+
+ try {
+ await Promise.race([
+ new Promise<void>((resolve) => {
+ onError = resolve;
+ childProcess.once('error', onError);
+ }),
+ new Promise<void>((resolve) => {
+ onExit = resolve;
+ childProcess.once('exit', onExit);
+ }),
+ new Promise<void>((resolve) => {
+ timer = setTimeout(resolve, waitTimeout);
+ }),
+ ]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ if (onError) childProcess.off('error', onError);
+ if (onExit) childProcess.off('exit', onExit);
+ }
+ }
+ }
+
+ exitCode = childProcess.exitCode ?? shellProcess.exitCode;
+
const newStdout = stdout.slice(lastReadStdout).join('');
const newStderr = stderr.slice(lastReadStderr).join('');
let output = newStdout + newStderr;
@@ -50,11 +99,9 @@ export class ShellProcessManager {
shellProcess.lastReadStdout = stdout.length;
shellProcess.lastReadStderr = stderr.length;
- const running = childProcess.exitCode === null;
-
return {
+ exit_code: exitCode ?? undefined,
output: truncateOutput(output),
- running,
stderr: truncateOutput(newStderr),
stdout: truncateOutput(newStdout),
success: true,
diff --git a/packages/local-file-shell/src/shell/runner.ts b/packages/local-file-shell/src/shell/runner.ts
index de559fe5222..a43ba2ec31a 100644
--- a/packages/local-file-shell/src/shell/runner.ts
+++ b/packages/local-file-shell/src/shell/runner.ts
@@ -1,9 +1,8 @@
import { spawn } from 'node:child_process';
-import { randomUUID } from 'node:crypto';
import type { RunCommandParams, RunCommandResult } from '../types';
import type { ShellProcess, ShellProcessManager } from './process-manager';
-import { getShellConfig, truncateOutput } from './utils';
+import { getShellConfig } from './utils';
export interface RunCommandOptions {
logger?: {
@@ -21,7 +20,7 @@ export async function runCommand(
description,
env: extraEnv,
run_in_background,
- timeout = 120_000,
+ timeout = 30_000,
}: RunCommandParams,
{ processManager, logger }: RunCommandOptions,
): Promise<RunCommandResult> {
@@ -32,101 +31,61 @@ export async function runCommand(
const logPrefix = `[runCommand: ${description || command.slice(0, 50)}]`;
logger?.debug(`${logPrefix} Starting`, { background: run_in_background, cwd, timeout });
- const effectiveTimeout = Math.min(Math.max(timeout, 1000), 800_000);
const shellConfig = getShellConfig(command);
const childEnv = extraEnv ? { ...process.env, ...extraEnv } : process.env;
try {
- if (run_in_background) {
- const shellId = randomUUID();
- const childProcess = spawn(shellConfig.cmd, shellConfig.args, {
- cwd,
- env: childEnv,
- shell: false,
- });
-
- const shellProcess: ShellProcess = {
- lastReadStderr: 0,
- lastReadStdout: 0,
- process: childProcess,
- stderr: [],
- stdout: [],
- };
-
- childProcess.stdout?.on('data', (data) => {
- shellProcess.stdout.push(data.toString());
- });
-
- childProcess.stderr?.on('data', (data) => {
- shellProcess.stderr.push(data.toString());
- });
+ const shellId = processManager.createShellId();
+ const childProcess = spawn(shellConfig.cmd, shellConfig.args, {
+ cwd,
+ env: childEnv,
+ shell: false,
+ });
+
+ const shellProcess: ShellProcess = {
+ exitCode: null,
+ lastReadStderr: 0,
+ lastReadStdout: 0,
+ process: childProcess,
+ stderr: [],
+ stdout: [],
+ };
+
+ childProcess.stdout?.on('data', (data) => {
+ shellProcess.stdout.push(data.toString());
+ });
+
+ childProcess.stderr?.on('data', (data) => {
+ shellProcess.stderr.push(data.toString());
+ });
+
+ childProcess.on('exit', (code) => {
+ logger?.debug(`${logPrefix} Process exited`, { code, shellId });
+ shellProcess.exitCode = code ?? 0;
+ });
+
+ childProcess.on('error', (error) => {
+ logger?.error(`${logPrefix} Command failed:`, error);
+ shellProcess.stderr.push(error.message);
+ shellProcess.exitCode = 1;
+ });
+
+ processManager.register(shellId, shellProcess);
+ logger?.info?.(`${logPrefix} Started session`, { background: run_in_background, shellId });
- childProcess.on('exit', (code) => {
- logger?.debug(`${logPrefix} Background process exited`, { code, shellId });
- });
-
- processManager.register(shellId, shellProcess);
-
- logger?.info?.(`${logPrefix} Started background`, { shellId });
+ if (run_in_background) {
return { shell_id: shellId, success: true };
- } else {
- return new Promise<RunCommandResult>((resolve) => {
- const childProcess = spawn(shellConfig.cmd, shellConfig.args, {
- cwd,
- env: childEnv,
- shell: false,
- });
-
- let stdout = '';
- let stderr = '';
- let killed = false;
-
- const timeoutHandle = setTimeout(() => {
- killed = true;
- childProcess.kill();
- resolve({
- error: `Command timed out after ${effectiveTimeout}ms`,
- stderr: truncateOutput(stderr),
- stdout: truncateOutput(stdout),
- success: false,
- });
- }, effectiveTimeout);
-
- childProcess.stdout?.on('data', (data) => {
- stdout += data.toString();
- });
-
- childProcess.stderr?.on('data', (data) => {
- stderr += data.toString();
- });
+ }
- childProcess.on('exit', (code) => {
- if (!killed) {
- clearTimeout(timeoutHandle);
- const success = code === 0;
- logger?.info?.(`${logPrefix} Command completed`, { code, success });
- resolve({
- exit_code: code || 0,
- output: truncateOutput(stdout + stderr),
- stderr: truncateOutput(stderr),
- stdout: truncateOutput(stdout),
- success,
- });
- }
- });
+ const observation = await processManager.getOutput({
+ shell_id: shellId,
+ timeout,
+ });
- childProcess.on('error', (error) => {
- clearTimeout(timeoutHandle);
- logger?.error(`${logPrefix} Command failed:`, error);
- resolve({
- error: error.message,
- stderr: truncateOutput(stderr),
- stdout: truncateOutput(stdout),
- success: false,
- });
- });
- });
- }
+ return {
+ ...observation,
+ shell_id: shellId,
+ };
} catch (error) {
return { error: (error as Error).message, success: false };
}
diff --git a/packages/local-file-shell/src/types.ts b/packages/local-file-shell/src/types.ts
index 0afd411ad9b..cfdb5de9802 100644
--- a/packages/local-file-shell/src/types.ts
+++ b/packages/local-file-shell/src/types.ts
@@ -6,30 +6,61 @@ export interface RunCommandParams {
description?: string;
env?: Record<string, string>;
run_in_background?: boolean;
+ /**
+ * Maximum time to wait for this observation before returning.
+ * Does not kill the process when the timeout elapses.
+ */
timeout?: number;
}
export interface RunCommandResult {
error?: string;
+ /**
+ * Present only after the command has exited.
+ * `0` means success, non-zero means the command finished with an error.
+ * `undefined` means the command is still running.
+ */
exit_code?: number;
output?: string;
+ /**
+ * Session identifier. Present for background commands and foreground commands
+ * that can be resumed with `getCommandOutput`.
+ */
shell_id?: string;
stderr?: string;
stdout?: string;
+ /**
+ * True when the command/session request completed successfully.
+ * Use `exit_code` to determine whether the underlying command has exited.
+ */
success: boolean;
}
export interface GetCommandOutputParams {
filter?: string;
shell_id: string;
+ /**
+ * Maximum time to wait for this observation before returning.
+ * Does not kill the process when the timeout elapses.
+ */
+ timeout?: number;
}
export interface GetCommandOutputResult {
error?: string;
+ /**
+ * Present only after the command has exited.
+ * `0` means success, non-zero means the command finished with an error.
+ * `undefined` means the command is still running.
+ */
+ exit_code?: number;
output: string;
- running: boolean;
stderr: string;
stdout: string;
+ /**
+ * True when the output request completed successfully.
+ * Use `exit_code` to determine whether the underlying command has exited.
+ */
success: boolean;
}
diff --git a/packages/prompts/src/prompts/fileSystem/formatCommandOutput.test.ts b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.test.ts
index 74f01222be1..898d7660c73 100644
--- a/packages/prompts/src/prompts/fileSystem/formatCommandOutput.test.ts
+++ b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.test.ts
@@ -3,30 +3,35 @@ import { describe, expect, it } from 'vitest';
import { formatCommandOutput } from './formatCommandOutput';
describe('formatCommandOutput', () => {
- it('should format successful output while running', () => {
+ it('should format successful output without exit code', () => {
const result = formatCommandOutput({
- running: true,
success: true,
});
- expect(result).toMatchInlineSnapshot(`"Output retrieved. Running: true"`);
+ expect(result).toMatchInlineSnapshot(`"Output retrieved."`);
});
- it('should format successful output when not running', () => {
+ it('should include exit code when present', () => {
const result = formatCommandOutput({
- running: false,
+ exitCode: 0,
success: true,
});
- expect(result).toMatchInlineSnapshot(`"Output retrieved. Running: false"`);
+ expect(result).toMatchInlineSnapshot(`
+ "Output retrieved.
+
+ Exit code: 0"
+ `);
});
it('should format successful output with content', () => {
const result = formatCommandOutput({
+ exitCode: 17,
output: 'Process output here',
- running: true,
success: true,
});
expect(result).toMatchInlineSnapshot(`
- "Output retrieved. Running: true
+ "Output retrieved.
+
+ Exit code: 17
Output:
Process output here"
@@ -36,7 +41,6 @@ describe('formatCommandOutput', () => {
it('should format failed output', () => {
const result = formatCommandOutput({
error: 'Process not found',
- running: false,
success: false,
});
expect(result).toMatchInlineSnapshot(`"Failed: Process not found"`);
@@ -45,12 +49,14 @@ describe('formatCommandOutput', () => {
it('should format successful output with error info', () => {
const result = formatCommandOutput({
error: 'Warning message',
+ exitCode: 1,
output: 'Some output',
- running: false,
success: true,
});
expect(result).toMatchInlineSnapshot(`
- "Output retrieved. Running: false
+ "Output retrieved.
+
+ Exit code: 1
Output:
Some output
diff --git a/packages/prompts/src/prompts/fileSystem/formatCommandOutput.ts b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.ts
index fbca330f385..40212727631 100644
--- a/packages/prompts/src/prompts/fileSystem/formatCommandOutput.ts
+++ b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.ts
@@ -1,19 +1,20 @@
export interface FormatCommandOutputParams {
error?: string;
+ exitCode?: number;
output?: string;
- running: boolean;
success: boolean;
}
export const formatCommandOutput = ({
success,
- running,
+ exitCode,
output,
error,
}: FormatCommandOutputParams): string => {
- const message = success ? `Output retrieved. Running: ${running}` : `Failed: ${error}`;
+ const message = success ? 'Output retrieved.' : `Failed: ${error}`;
const parts: string[] = [message];
+ if (exitCode !== undefined) parts.push(`Exit code: ${exitCode}`);
if (output) parts.push(`Output:\n${output}`);
if (error && success) parts.push(`Error: ${error}`);
diff --git a/packages/tool-runtime/src/ComputerRuntime.ts b/packages/tool-runtime/src/ComputerRuntime.ts
index 34e85eb31e2..96eb60331d8 100644
--- a/packages/tool-runtime/src/ComputerRuntime.ts
+++ b/packages/tool-runtime/src/ComputerRuntime.ts
@@ -341,7 +341,6 @@ export abstract class ComputerRuntime {
if (!result.success) {
return this.errorOutput(result, {
error: result.error?.message,
- running: false,
success: false,
});
}
@@ -350,15 +349,15 @@ export abstract class ComputerRuntime {
const state: GetCommandOutputState = {
error: r.error,
+ exitCode: r.exitCode ?? r.exit_code,
newOutput: r.newOutput || r.output,
- running: r.running ?? false,
success: result.success,
};
const content = formatCommandOutput({
error: r.error,
+ exitCode: r.exitCode ?? r.exit_code,
output: r.newOutput || r.output,
- running: r.running ?? false,
success: result.success,
});
diff --git a/packages/tool-runtime/src/types.ts b/packages/tool-runtime/src/types.ts
index 1992b9bf4c1..4827f00c0a7 100644
--- a/packages/tool-runtime/src/types.ts
+++ b/packages/tool-runtime/src/types.ts
@@ -188,8 +188,8 @@ export interface RunCommandState {
export interface GetCommandOutputState {
error?: string;
+ exitCode?: number;
newOutput?: string;
- running: boolean;
success: boolean;
}
diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
index c6d45f6d88b..74c295872ee 100644
--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
@@ -1873,6 +1873,11 @@ export const createRuntimeExecutors = (
chatToolPayload.source = toolSource;
}
+ const timeoutMs = resolveToolTimeoutMs({
+ apiName: chatToolPayload.apiName,
+ args: parsedArgs,
+ manifest: effectiveManifestMap[chatToolPayload.identifier],
+ });
// Execute tool using ToolExecutionService
log(`[${operationLogId}] Executing tool ${toolName} ...`);
execution = await executeToolWithRetry(
@@ -1881,6 +1886,7 @@ export const createRuntimeExecutors = (
activeDeviceId: state.metadata?.activeDeviceId,
agentId: state.metadata?.agentId,
documentId: state.metadata?.documentId,
+ executionTimeoutMs: timeoutMs,
groupId: state.metadata?.groupId,
memoryToolPermission: agentConfig?.chatConfig?.memory?.toolPermission,
messageId: state.metadata?.sourceMessageId,
@@ -2400,12 +2406,19 @@ export const createRuntimeExecutors = (
chatToolPayload.source = batchToolSource;
}
+ const timeoutMs = resolveToolTimeoutMs({
+ apiName: chatToolPayload.apiName,
+ args: batchParsedArgs,
+ manifest: batchManifestMap[chatToolPayload.identifier],
+ });
+
execution = await executeToolWithRetry(
() =>
toolExecutionService.executeTool(chatToolPayload, {
activeDeviceId: state.metadata?.activeDeviceId,
agentId: state.metadata?.agentId,
documentId: state.metadata?.documentId,
+ executionTimeoutMs: timeoutMs,
groupId: state.metadata?.groupId,
memoryToolPermission: batchAgentConfig?.chatConfig?.memory?.toolPermission,
messageId: state.metadata?.sourceMessageId,
diff --git a/src/server/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts b/src/server/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
index 3a286161126..88d96b5480f 100644
--- a/src/server/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
+++ b/src/server/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
@@ -1,5 +1,5 @@
import { LocalSystemIdentifier, LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { type ToolExecutionContext } from '../../types';
@@ -15,6 +15,10 @@ vi.mock('../../deviceProxy', () => ({
const { localSystemRuntime } = await import('../localSystem');
describe('localSystemRuntime', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
it('should have the correct identifier', () => {
expect(localSystemRuntime.identifier).toBe(LocalSystemIdentifier);
});
@@ -80,6 +84,7 @@ describe('localSystemRuntime', () => {
arguments: JSON.stringify(args),
identifier: LocalSystemIdentifier,
},
+ undefined,
);
expect(result).toEqual(expectedResult);
});
@@ -104,6 +109,7 @@ describe('localSystemRuntime', () => {
expect.objectContaining({
arguments: JSON.stringify(complexArgs),
}),
+ undefined,
);
});
});
diff --git a/src/server/services/toolExecution/serverRuntimes/localSystem.ts b/src/server/services/toolExecution/serverRuntimes/localSystem.ts
index d688b9d9852..6a8c625b83b 100644
--- a/src/server/services/toolExecution/serverRuntimes/localSystem.ts
+++ b/src/server/services/toolExecution/serverRuntimes/localSystem.ts
@@ -23,6 +23,7 @@ export const localSystemRuntime: ServerRuntimeRegistration = {
arguments: JSON.stringify(args),
identifier: LocalSystemIdentifier,
},
+ context.executionTimeoutMs,
);
};
}
diff --git a/src/server/services/toolExecution/types.ts b/src/server/services/toolExecution/types.ts
index 1a96824a5d9..01daaccf331 100644
--- a/src/server/services/toolExecution/types.ts
+++ b/src/server/services/toolExecution/types.ts
@@ -18,6 +18,8 @@ export interface ToolExecutionContext {
agentId?: string;
/** Current page document ID for page-scoped conversations */
documentId?: string | null;
+ /** Per-call execution timeout resolved by the agent runtime. */
+ executionTimeoutMs?: number;
/** Current group ID for group chat context */
groupId?: string | null;
/**