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: clarify local system shell result wording (#15745)

Rylan Cai99023811d88f
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index f0a79b5e762..afe91b5a8c8 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -262,19 +262,23 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
// Handle tool call requests
client.on('tool_call_request', async (request: ToolCallRequestMessage) => {
- const { requestId, timeout, toolCall } = request;
+ const { operationId, requestId, timeout, toolCall } = request;
if (isDaemonChild) {
- appendLog(`[TOOL] ${toolCall.apiName} (${requestId})`);
+ appendLog(
+ `[TOOL] ${toolCall.apiName}${operationId ? ` op=${operationId}` : ''} (${requestId})`,
+ );
} else {
- log.toolCall(toolCall.apiName, requestId, toolCall.arguments);
+ log.toolCall(toolCall.apiName, requestId, toolCall.arguments, operationId);
}
const result = await executeToolCall(toolCall.apiName, toolCall.arguments, timeout);
if (isDaemonChild) {
- appendLog(`[RESULT] ${result.success ? 'OK' : 'FAIL'} (${requestId})`);
+ appendLog(
+ `[RESULT] ${result.success ? 'OK' : 'FAIL'}${operationId ? ` op=${operationId}` : ''} (${requestId})`,
+ );
} else {
- log.toolResult(requestId, result.success, result.content);
+ log.toolResult(requestId, result.success, result.content, operationId);
}
client.sendToolCallResponse({
diff --git a/apps/cli/src/utils/logger.ts b/apps/cli/src/utils/logger.ts
index 04cf74dc74a..b6bfca39acc 100644
--- a/apps/cli/src/utils/logger.ts
+++ b/apps/cli/src/utils/logger.ts
@@ -1,4 +1,3 @@
-/* eslint-disable no-console */
import pc from 'picocolors';
let verbose = false;
@@ -41,18 +40,20 @@ export const log = {
console.log(`${timestamp()} ${pc.bold('[STATUS]')} ${color(status)}`);
},
- toolCall: (apiName: string, requestId: string, args?: string) => {
+ toolCall: (apiName: string, requestId: string, args?: string, operationId?: string) => {
console.log(
- `${timestamp()} ${pc.magenta('[TOOL]')} ${pc.bold(apiName)} ${pc.dim(`(${requestId})`)}`,
+ `${timestamp()} ${pc.magenta('[TOOL]')} ${pc.bold(apiName)}${operationId ? ` ${pc.dim(`op=${operationId}`)}` : ''} ${pc.dim(`(${requestId})`)}`,
);
if (args && verbose) {
console.log(` ${pc.dim(args)}`);
}
},
- toolResult: (requestId: string, success: boolean, content?: string) => {
+ toolResult: (requestId: string, success: boolean, content?: string, operationId?: string) => {
const icon = success ? pc.green('OK') : pc.red('FAIL');
- console.log(`${timestamp()} ${pc.magenta('[RESULT]')} ${icon} ${pc.dim(`(${requestId})`)}`);
+ console.log(
+ `${timestamp()} ${pc.magenta('[RESULT]')} ${icon}${operationId ? ` ${pc.dim(`op=${operationId}`)}` : ''} ${pc.dim(`(${requestId})`)}`,
+ );
if (content && verbose) {
const preview = content.length > 200 ? content.slice(0, 200) + '...' : content;
console.log(` ${pc.dim(preview)}`);
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index 949b929aab6..f67a256d1c4 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -669,7 +669,7 @@ export class DeviceGateway {
}
async executeToolCall(
- params: { deviceId: string; userId: string },
+ params: { deviceId: string; operationId?: string; userId: string },
toolCall: { apiName: string; arguments: string; identifier: string },
timeout = 30_000,
): Promise<DeviceToolCallResult> {
@@ -683,7 +683,8 @@ export class DeviceGateway {
}
log(
- 'executeToolCall: userId=%s, deviceId=%s, tool=%s/%s',
+ 'executeToolCall: operationId=%s, userId=%s, deviceId=%s, tool=%s/%s',
+ params.operationId ?? 'N/A',
params.userId,
params.deviceId,
toolCall.identifier,
@@ -692,7 +693,12 @@ export class DeviceGateway {
try {
return await client.executeToolCall(
- { deviceId: params.deviceId, timeout, userId: params.userId },
+ {
+ deviceId: params.deviceId,
+ operationId: params.operationId,
+ timeout,
+ userId: params.userId,
+ },
toolCall,
);
} catch (error) {
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
index a25e1e4baa1..e2a1967b67b 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
@@ -64,6 +64,7 @@ describe('localSystemRuntime', () => {
it('should call deviceGateway.executeToolCall with correct arguments when a proxy function is invoked', async () => {
const context: ToolExecutionContext = {
activeDeviceId: 'device-1',
+ operationId: 'op-1',
toolManifestMap: {},
userId: 'user-1',
};
@@ -78,7 +79,7 @@ describe('localSystemRuntime', () => {
const result = await proxy[apiName](args);
expect(mockExecuteToolCall).toHaveBeenCalledWith(
- { deviceId: 'device-1', userId: 'user-1' },
+ { deviceId: 'device-1', operationId: 'op-1', userId: 'user-1' },
{
apiName,
arguments: JSON.stringify(args),
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
index 96ac637c2b6..d3eb7c22008 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
@@ -18,7 +18,11 @@ export const localSystemRuntime: ServerRuntimeRegistration = {
for (const api of LocalSystemManifest.api) {
proxy[api.name] = async (args: any) => {
return deviceGateway.executeToolCall(
- { deviceId: context.activeDeviceId!, userId: context.userId! },
+ {
+ deviceId: context.activeDeviceId!,
+ operationId: context.operationId,
+ userId: context.userId!,
+ },
{
apiName: api.name,
arguments: JSON.stringify(args),
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
index ef732eca813..11a452fc56b 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
@@ -1,7 +1,7 @@
import { builtinSkills } from '@lobechat/builtin-skills';
import { LocalSystemApiName, LocalSystemIdentifier } from '@lobechat/builtin-tool-local-system';
// Note: only `readFile` is wired through deviceGateway. Directory enumeration is
-// left to the model via `local-system.listFiles` so we don't double-fetch.
+// left to the model via `local-system.globFiles` so we don't double-fetch.
import {
type CommandResult,
type ExecScriptActivatedSkill,
diff --git a/packages/builtin-tool-local-system/src/manifest.ts b/packages/builtin-tool-local-system/src/manifest.ts
index 885cb9629bd..f13f8ae3191 100644
--- a/packages/builtin-tool-local-system/src/manifest.ts
+++ b/packages/builtin-tool-local-system/src/manifest.ts
@@ -6,46 +6,6 @@ import { LocalSystemApiName, LocalSystemIdentifier } from './types';
export const LocalSystemManifest: BuiltinToolManifest = {
executors: ['client', 'server'],
api: [
- {
- defaultTimeoutMs: 30_000,
- description:
- 'List files and folders in a specified directory. Input should be a path. Output is a JSON array of file/folder names.',
- humanIntervention: {
- dynamic: {
- default: 'never',
- policy: 'required',
- type: 'pathScopeAudit',
- },
- },
- name: LocalSystemApiName.listFiles,
- parameters: {
- properties: {
- limit: {
- default: 100,
- description: 'Maximum number of items to return (default: 100)',
- type: 'number',
- },
- path: {
- description: 'The directory path to list',
- type: 'string',
- },
- sortBy: {
- default: 'modifiedTime',
- description: 'Field to sort by (default: modifiedTime)',
- enum: ['name', 'modifiedTime', 'createdTime', 'size'],
- type: 'string',
- },
- sortOrder: {
- default: 'desc',
- description: 'Sort order (default: desc)',
- enum: ['asc', 'desc'],
- type: 'string',
- },
- },
- required: ['path'],
- type: 'object',
- },
- },
{
defaultTimeoutMs: 30_000,
description:
@@ -265,7 +225,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {
{
defaultTimeoutMs: 30_000,
description:
- 'Start a terminal session to execute a shell command and return console output collected during the wait window (up to 30 seconds by default). 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.',
+ 'Start a terminal session to execute a shell command and return console output collected during the wait window (up to 30 seconds by default). 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: {
diff --git a/packages/builtin-tool-local-system/src/systemRole.desktop.ts b/packages/builtin-tool-local-system/src/systemRole.desktop.ts
index 76576044647..1de0c2eceb2 100644
--- a/packages/builtin-tool-local-system/src/systemRole.desktop.ts
+++ b/packages/builtin-tool-local-system/src/systemRole.desktop.ts
@@ -1,4 +1,4 @@
-export const systemPrompt = `You have a Local System tool with capabilities to interact with the user's local system. You can list directories, read file contents, search for files, move, and rename files/directories.
+export const systemPrompt = `You have a Local System tool with capabilities to interact with the user's local system. You can read file contents, search for files, move and rename files/directories, and run shell commands.
<user_context>
**Current Working Directory:** {{workingDirectory}}
@@ -21,27 +21,26 @@ Use these paths when the user refers to these common locations by name (e.g., "m
You have access to a set of tools to interact with the user's local file system:
**File Operations:**
-1. **listFiles**: Lists files and directories in a specified path. Returns metadata including file size and modification time. Results are sorted by modification time (newest first) by default and limited to 100 items.
-2. **readFile**: Reads the content of a specified file, optionally within a line range. You can read file types such as Word, Excel, PowerPoint, PDF, and plain text files.
-3. **writeFile**: Write content to a specific file, only support plain text file like \`.text\` or \`.md\`
-4. **editFile**: Performs exact string replacements in files. Must read the file first before editing.
-5. **moveFiles**: Moves multiple files or directories. Also handles renames β€” pass the original directory with the new filename in \`newPath\`.
+1. **readFile**: Reads the content of a specified file, optionally within a line range. You can read file types such as Word, Excel, PowerPoint, PDF, and plain text files.
+2. **writeFile**: Write content to a specific file, only support plain text file like \`.text\` or \`.md\`
+3. **editFile**: Performs exact string replacements in files. Must read the file first before editing.
+4. **moveFiles**: Moves multiple files or directories. Also handles renames β€” pass the original directory with the new filename in \`newPath\`.
**Shell Commands:**
-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.
+5. **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.
+6. **getCommandOutput**: Retrieve output from an existing terminal session. Returns only new output since last check.
+7. **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.
-10. **grepContent**: Search for content within files using regex patterns. Supports various output modes, filtering, and context lines.
-11. **globFiles**: Find files matching glob patterns (e.g., "**/*.js", "*.{ts,tsx}").
+8. **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.
+9. **grepContent**: Search for content within files using regex patterns. Supports various output modes, filtering, and context lines.
+10. **globFiles**: Find files matching glob patterns (e.g., "**/*.js", "*.{ts,tsx}").
</core_capabilities>
<workflow>
1. Understand the user's request regarding local operations (files, commands, searches).
2. Select the appropriate tool:
- - File operations: listFiles, readFile, writeFile, editFile, moveFiles
+ - File operations: readFile, writeFile, editFile, moveFiles
- Shell commands: runCommand, getCommandOutput, killCommand
- Search/Find: searchFiles, grepContent, globFiles
3. Execute the operation. **If the user mentions a common location (like Desktop, Documents, Downloads, etc.) without providing a full path, use the corresponding path from the <user_context> section.**
@@ -49,13 +48,6 @@ You have access to a set of tools to interact with the user's local file system:
</workflow>
<tool_usage_guidelines>
-- For listing directory contents: Use 'listFiles'. Provide the following parameters:
- - 'path': The directory path to list.
- - 'sortBy' (Optional): Field to sort results by. Options: 'name', 'modifiedTime', 'createdTime', 'size'. Defaults to 'modifiedTime'.
- - 'sortOrder' (Optional): Sort order. Options: 'asc', 'desc'. Defaults to 'desc' (newest/largest first).
- - 'limit' (Optional): Maximum number of items to return. Defaults to 100.
- - The response includes file/folder names with metadata (size in bytes, modification time) for each item.
- - System files (e.g., '.DS_Store', 'Thumbs.db', '$RECYCLE.BIN') are automatically filtered out.
- For reading a file: Use 'readFile'. Provide the following parameters:
- 'path': The exact file path.
- 'loc' (Optional): A two-element array [startLine, endLine] to specify a line range to read (e.g., '[301, 400]' reads lines 301 to 400).
@@ -90,7 +82,6 @@ You have access to a set of tools to interact with the user's local file system:
- 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.
@@ -99,7 +90,7 @@ You have access to a set of tools to interact with the user's local file system:
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 remote device execution feedback: 'Device tool call failed (HTTP ...)' describes the remote-device/gateway layer, not necessarily the local operation.
- HTTP 403 likely means an edge security policy blocked the request; replan with an equivalent approach or another tool such as runCommand.
- - HTTP 503 is usually transient; retry when the operation is safe to repeat.
+ - HTTP 503 is usually transient during reconnects or stale session replacement. For the same intended operation, retry up to 8 times only when the operation is safe to repeat; if it still fails, stop retrying that operation and replan.
- HTTP 504 means the device did not respond within the wait window; the command may already have started, so retry only when the operation is safe to repeat.
- For searching content in files: Use 'grepContent'. Provide:
- 'pattern': The regex pattern to search for.
diff --git a/packages/builtin-tool-local-system/src/systemRole.ts b/packages/builtin-tool-local-system/src/systemRole.ts
index 34c25714595..3c293b60b60 100644
--- a/packages/builtin-tool-local-system/src/systemRole.ts
+++ b/packages/builtin-tool-local-system/src/systemRole.ts
@@ -1,4 +1,4 @@
-export const systemPrompt = `You have a Local System tool with capabilities to interact with the user's local system. You can list directories, read file contents, search for files, move, and rename files/directories.
+export const systemPrompt = `You have a Local System tool with capabilities to interact with the user's local system. You can read file contents, search for files, move and rename files/directories, and run shell commands.
<user_context>
<device name="{{hostname}}" os="{{platform}}" arch="{{arch}}" />
@@ -10,27 +10,26 @@ export const systemPrompt = `You have a Local System tool with capabilities to i
You have access to a set of tools to interact with the user's local file system:
**File Operations:**
-1. **listFiles**: Lists files and directories in a specified path. Returns metadata including file size and modification time. Results are sorted by modification time (newest first) by default and limited to 100 items.
-2. **readFile**: Reads the content of a specified file, optionally within a line range. You can read file types such as Word, Excel, PowerPoint, PDF, and plain text files.
-3. **writeFile**: Write content to a specific file, only support plain text file like \`.text\` or \`.md\`
-4. **editFile**: Performs exact string replacements in files. Must read the file first before editing.
-5. **moveFiles**: Moves multiple files or directories. Also handles renames β€” pass the original directory with the new filename in \`newPath\`.
+1. **readFile**: Reads the content of a specified file, optionally within a line range. You can read file types such as Word, Excel, PowerPoint, PDF, and plain text files.
+2. **writeFile**: Write content to a specific file, only support plain text file like \`.text\` or \`.md\`
+3. **editFile**: Performs exact string replacements in files. Must read the file first before editing.
+4. **moveFiles**: Moves multiple files or directories. Also handles renames β€” pass the original directory with the new filename in \`newPath\`.
**Shell Commands:**
-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.
+5. **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.
+6. **getCommandOutput**: Retrieve output from an existing terminal session. Returns only new output since last check.
+7. **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.
-10. **grepContent**: Search for content within files using regex patterns. Supports various output modes, filtering, and context lines.
-11. **globFiles**: Find files matching glob patterns (e.g., "**/*.js", "*.{ts,tsx}").
+8. **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.
+9. **grepContent**: Search for content within files using regex patterns. Supports various output modes, filtering, and context lines.
+10. **globFiles**: Find files matching glob patterns (e.g., "**/*.js", "*.{ts,tsx}").
</core_capabilities>
<workflow>
1. Understand the user's request regarding local operations (files, commands, searches).
2. Select the appropriate tool:
- - File operations: listFiles, readFile, writeFile, editFile, moveFiles
+ - File operations: readFile, writeFile, editFile, moveFiles
- Shell commands: runCommand, getCommandOutput, killCommand
- Search/Find: searchFiles, grepContent, globFiles
3. Execute the operation. **If the user mentions a common location (like Desktop, Documents, Downloads, etc.) without providing a full path, use the corresponding path from the <user_context> section.**
@@ -38,13 +37,6 @@ You have access to a set of tools to interact with the user's local file system:
</workflow>
<tool_usage_guidelines>
-- For listing directory contents: Use 'listFiles'. Provide the following parameters:
- - 'path': The directory path to list.
- - 'sortBy' (Optional): Field to sort results by. Options: 'name', 'modifiedTime', 'createdTime', 'size'. Defaults to 'modifiedTime'.
- - 'sortOrder' (Optional): Sort order. Options: 'asc', 'desc'. Defaults to 'desc' (newest/largest first).
- - 'limit' (Optional): Maximum number of items to return. Defaults to 100.
- - The response includes file/folder names with metadata (size in bytes, modification time) for each item.
- - System files (e.g., '.DS_Store', 'Thumbs.db', '$RECYCLE.BIN') are automatically filtered out.
- For reading a file: Use 'readFile'. Provide the following parameters:
- 'path': The exact file path.
- 'loc' (Optional): A two-element array [startLine, endLine] to specify a line range to read (e.g., '[301, 400]' reads lines 301 to 400).
@@ -79,7 +71,6 @@ You have access to a set of tools to interact with the user's local file system:
- 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.
@@ -88,7 +79,7 @@ You have access to a set of tools to interact with the user's local file system:
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 remote device execution feedback: 'Device tool call failed (HTTP ...)' describes the remote-device/gateway layer, not necessarily the local operation.
- HTTP 403 likely means an edge security policy blocked the request; replan with an equivalent approach or another tool such as runCommand.
- - HTTP 503 is usually transient; retry when the operation is safe to repeat.
+ - HTTP 503 is usually transient during reconnects or stale session replacement. For the same intended operation, retry up to 8 times only when the operation is safe to repeat; if it still fails, stop retrying that operation and replan.
- HTTP 504 means the device did not respond within the wait window; the command may already have started, so retry only when the operation is safe to repeat.
- For searching content in files: Use 'grepContent'. Provide:
- 'pattern': The regex pattern to search for.
diff --git a/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts
index 1cb9982dfd9..126a554d0dc 100644
--- a/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts
+++ b/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts
@@ -204,9 +204,9 @@ describe('SkillsExecutionRuntime', () => {
expect(result.success).toBe(true);
expect(result.content).toContain('Run the deploy steps.');
// The hint points at the skill's directory and instructs the model to
- // call `local-system.listFiles` itself rather than pre-enumerating here.
+ // call `local-system.globFiles` itself rather than pre-enumerating here.
expect(result.content).toContain('/repo/.agents/skills/deploy');
- expect(result.content).toContain('listFiles');
+ expect(result.content).toContain('globFiles');
expect(result.state).toMatchObject({ name: 'deploy', source: 'project' });
});
diff --git a/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts b/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts
index ddd36c5b358..f4300c01e03 100644
--- a/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts
@@ -124,13 +124,13 @@ const hasHiddenSegment = (rel: string): boolean =>
/**
* Hint appended to activated project-skill content so the model knows how to
* discover the rest of the skill's directory. We deliberately don't enumerate
- * the tree here β€” the model has `local-system.listFiles` available and can
+ * the tree here β€” the model has `local-system.globFiles` available and can
* call it on demand, which keeps the op-param payload small.
*/
const buildProjectDirectoryHint = (skillName: string, skillDir: string): string =>
`## Skill resources
-This project skill lives in \`${skillDir}\`. Use \`local-system.listFiles\` on that path to discover reference files, then \`readReference\` with skillName="${skillName}" + the relative path to load any of them.`;
+This project skill lives in \`${skillDir}\`. Use \`local-system.globFiles\` with scope="${skillDir}" and pattern="**/*" to discover reference files, then \`readReference\` with skillName="${skillName}" + the relative path to load any of them.`;
export class SkillsExecutionRuntime {
private builtinSkills: BuiltinSkill[];
@@ -378,7 +378,7 @@ export class SkillsExecutionRuntime {
let content = await this.deviceFileAccess.readFile(projectSkill.location);
// Don't enumerate the directory here β€” let the model do it on demand
- // via `local-system.listFiles`. Just point at the skill's directory so
+ // via `local-system.globFiles`. Just point at the skill's directory so
// it knows where to look. Keeps the op-param payload small and avoids
// a second deviceGateway round-trip at activation time.
const skillDir = getDirname(projectSkill.location);
diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.ts
index 6d5e59f7669..b227020a6c2 100644
--- a/packages/device-gateway-client/src/http.test.ts
+++ b/packages/device-gateway-client/src/http.test.ts
@@ -274,6 +274,22 @@ describe('GatewayHttpClient', () => {
expect(body.toolCall.type).toBe('tool');
});
+ it('should pass optional operationId', async () => {
+ mockFetch({
+ json: vi.fn().mockResolvedValue({ content: 'ok', success: true }),
+ ok: true,
+ });
+
+ await client.executeToolCall(
+ { operationId: 'op-1', userId: 'user-1' },
+ { apiName: 'readFile', arguments: '{}', identifier: 'test' },
+ );
+
+ const init = vi.mocked(fetch).mock.calls[0][1];
+ const body = JSON.parse((init as RequestInit).body as string);
+ expect(body.operationId).toBe('op-1');
+ });
+
it('should use default gateway timeout plus HTTP caller padding when timeout is absent', async () => {
mockFetch({
json: vi.fn().mockResolvedValue({ content: 'ok', success: true }),
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index 23170357895..8253a7e61af 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -66,7 +66,7 @@ export class GatewayHttpClient {
}
async executeToolCall(
- params: { deviceId?: string; timeout?: number; userId: string },
+ params: { deviceId?: string; operationId?: string; timeout?: number; userId: string },
toolCall: { apiName: string; arguments: string; identifier: string },
): Promise<DeviceToolCallResult> {
return this.postToolCall(params, { ...toolCall, type: 'tool' });
@@ -95,7 +95,7 @@ export class GatewayHttpClient {
}
private async postToolCall(
- params: { deviceId?: string; timeout?: number; userId: string },
+ params: { deviceId?: string; operationId?: string; timeout?: number; userId: string },
toolCall: {
apiName: string;
arguments: string;
@@ -112,6 +112,7 @@ export class GatewayHttpClient {
'/api/device/tool-call',
{
deviceId: params.deviceId,
+ operationId: params.operationId,
timeout: params.timeout,
toolCall,
userId: params.userId,
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 490acffc889..aa8a8851b70 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
@@ -190,6 +190,41 @@ describe('ShellProcessManager', () => {
expect(result.exit_code).toBe(0);
});
+ it('should report elapsed duration while the process is still running', async () => {
+ vi.useFakeTimers();
+ try {
+ const process = createMockProcess();
+ manager.register('test-1', createShellProcess(process));
+
+ await vi.advanceTimersByTimeAsync(42_000);
+
+ const result = await manager.getOutput({ shell_id: 'test-1', timeout: 0 });
+ expect(result.exit_code).toBeUndefined();
+ expect(result.duration_ms).toBe(42_000);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('should keep the final duration after the process exits', async () => {
+ vi.useFakeTimers();
+ try {
+ const process = createMockProcess();
+ manager.register('test-1', createShellProcess(process));
+
+ await vi.advanceTimersByTimeAsync(2500);
+ (process as { exitCode: number | null }).exitCode = 0;
+ process.emit('exit', 0);
+ await vi.advanceTimersByTimeAsync(7500);
+
+ const result = await manager.getOutput({ shell_id: 'test-1', timeout: 0 });
+ expect(result.exit_code).toBe(0);
+ expect(result.duration_ms).toBe(2500);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('should retain completed output after the process exits', async () => {
const process = createMockProcess();
manager.register('test-1', {
diff --git a/packages/local-file-shell/src/shell/process-manager.ts b/packages/local-file-shell/src/shell/process-manager.ts
index 5f3bc22217d..4880e433d5d 100644
--- a/packages/local-file-shell/src/shell/process-manager.ts
+++ b/packages/local-file-shell/src/shell/process-manager.ts
@@ -7,10 +7,12 @@ const DEFAULT_OBSERVATION_TIMEOUT_MS = 30_000;
const MAX_OBSERVATION_TIMEOUT_MS = 120_000;
export interface ShellProcess {
+ endedAt?: number;
exitCode: number | null;
lastReadStderr: number;
lastReadStdout: number;
process: ChildProcess;
+ startedAt?: number;
stderr: string[];
stdout: string[];
}
@@ -25,6 +27,17 @@ export class ShellProcessManager {
}
register(shellId: string, shellProcess: ShellProcess): void {
+ shellProcess.startedAt ??= Date.now();
+ if (shellProcess.exitCode !== null || shellProcess.process.exitCode !== null) {
+ shellProcess.endedAt ??= Date.now();
+ }
+
+ const markEnded = () => {
+ shellProcess.endedAt ??= Date.now();
+ };
+
+ shellProcess.process.once('exit', markEnded);
+ shellProcess.process.once('error', markEnded);
this.processes.set(shellId, shellProcess);
}
@@ -81,6 +94,9 @@ export class ShellProcessManager {
}
exitCode = childProcess.exitCode ?? shellProcess.exitCode;
+ if (exitCode !== null) {
+ shellProcess.endedAt ??= Date.now();
+ }
const newStdout = stdout.slice(lastReadStdout).join('');
const newStderr = stderr.slice(lastReadStderr).join('');
@@ -98,8 +114,11 @@ export class ShellProcessManager {
shellProcess.lastReadStdout = stdout.length;
shellProcess.lastReadStderr = stderr.length;
+ const startedAt = shellProcess.startedAt ?? Date.now();
+ const durationMs = Math.max(0, (shellProcess.endedAt ?? Date.now()) - startedAt);
return {
+ duration_ms: durationMs,
exit_code: exitCode ?? undefined,
output: truncateOutput(output),
stderr: truncateOutput(newStderr),
diff --git a/packages/local-file-shell/src/types.ts b/packages/local-file-shell/src/types.ts
index cfdb5de9802..ff6c1b6a9d1 100644
--- a/packages/local-file-shell/src/types.ts
+++ b/packages/local-file-shell/src/types.ts
@@ -47,6 +47,12 @@ export interface GetCommandOutputParams {
}
export interface GetCommandOutputResult {
+ /**
+ * Time in milliseconds from command start to this observation.
+ * For running commands, this is elapsed time at observation time.
+ * For completed commands, this is the final duration.
+ */
+ duration_ms?: number;
error?: string;
/**
* Present only after the command has exited.
diff --git a/packages/prompts/src/prompts/fileSystem/formatCommandOutput.test.ts b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.test.ts
index 898d7660c73..ed01796fe4c 100644
--- a/packages/prompts/src/prompts/fileSystem/formatCommandOutput.test.ts
+++ b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.test.ts
@@ -10,20 +10,29 @@ describe('formatCommandOutput', () => {
expect(result).toMatchInlineSnapshot(`"Output retrieved."`);
});
- it('should include exit code when present', () => {
+ it('should suppress zero exit code when present', () => {
const result = formatCommandOutput({
exitCode: 0,
success: true,
});
+ expect(result).toMatchInlineSnapshot(`"Output retrieved."`);
+ });
+
+ it('should format duration in seconds when present', () => {
+ const result = formatCommandOutput({
+ durationMs: 45_400,
+ success: true,
+ });
expect(result).toMatchInlineSnapshot(`
"Output retrieved.
- Exit code: 0"
+ Duration: 45s"
`);
});
- it('should format successful output with content', () => {
+ it('should format completed output with non-zero exit code', () => {
const result = formatCommandOutput({
+ durationMs: 123_000,
exitCode: 17,
output: 'Process output here',
success: true,
@@ -33,6 +42,8 @@ describe('formatCommandOutput', () => {
Exit code: 17
+ Duration: 123s
+
Output:
Process output here"
`);
diff --git a/packages/prompts/src/prompts/fileSystem/formatCommandOutput.ts b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.ts
index 40212727631..361ef243dda 100644
--- a/packages/prompts/src/prompts/fileSystem/formatCommandOutput.ts
+++ b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.ts
@@ -1,11 +1,18 @@
export interface FormatCommandOutputParams {
+ durationMs?: number;
error?: string;
exitCode?: number;
output?: string;
success: boolean;
}
+const formatDuration = (durationMs: number): string => {
+ const seconds = Math.max(0, Math.round(durationMs / 1000));
+ return `${seconds}s`;
+};
+
export const formatCommandOutput = ({
+ durationMs,
success,
exitCode,
output,
@@ -14,7 +21,10 @@ export const formatCommandOutput = ({
const message = success ? 'Output retrieved.' : `Failed: ${error}`;
const parts: string[] = [message];
- if (exitCode !== undefined) parts.push(`Exit code: ${exitCode}`);
+ if (exitCode !== undefined && exitCode !== 0) parts.push(`Exit code: ${exitCode}`);
+ if (durationMs !== undefined && Number.isFinite(durationMs)) {
+ parts.push(`Duration: ${formatDuration(durationMs)}`);
+ }
if (output) parts.push(`Output:\n${output}`);
if (error && success) parts.push(`Error: ${error}`);
diff --git a/packages/prompts/src/prompts/fileSystem/formatCommandResult.test.ts b/packages/prompts/src/prompts/fileSystem/formatCommandResult.test.ts
index 342b72776f7..27a8d967e27 100644
--- a/packages/prompts/src/prompts/fileSystem/formatCommandResult.test.ts
+++ b/packages/prompts/src/prompts/fileSystem/formatCommandResult.test.ts
@@ -4,22 +4,24 @@ import { formatCommandResult } from './formatCommandResult';
describe('formatCommandResult', () => {
it('should format successful command without output', () => {
- const result = formatCommandResult({ success: true });
+ const result = formatCommandResult({ exitCode: 0, success: true });
expect(result).toMatchInlineSnapshot(`"Command completed successfully."`);
});
- it('should format successful background command', () => {
+ it('should format still-running command', () => {
const result = formatCommandResult({
shellId: 'shell-123',
success: true,
});
- expect(result).toMatchInlineSnapshot(
- `"Command started in background with shell_id: shell-123"`,
- );
+ expect(result).toMatchInlineSnapshot(`
+ "Command is still running after the wait window.
+ shell_id: shell-123"
+ `);
});
it('should format successful command with stdout', () => {
const result = formatCommandResult({
+ exitCode: 0,
stdout: 'Hello World',
success: true,
});
@@ -33,6 +35,7 @@ describe('formatCommandResult', () => {
it('should format successful command with stderr', () => {
const result = formatCommandResult({
+ exitCode: 0,
stderr: 'Warning: deprecated',
success: true,
});
@@ -52,6 +55,15 @@ describe('formatCommandResult', () => {
expect(result).toMatchInlineSnapshot(`"Command completed successfully."`);
});
+ it('should treat shell id with exitCode 0 as completed', () => {
+ const result = formatCommandResult({
+ exitCode: 0,
+ shellId: 'shell-123',
+ success: true,
+ });
+ expect(result).toMatchInlineSnapshot(`"Command completed successfully."`);
+ });
+
it('should treat a non-zero exit code as failure even when envelope success is true', () => {
const result = formatCommandResult({
exitCode: 137,
diff --git a/packages/prompts/src/prompts/fileSystem/formatCommandResult.ts b/packages/prompts/src/prompts/fileSystem/formatCommandResult.ts
index 5004ec9b9bd..032c3da249c 100644
--- a/packages/prompts/src/prompts/fileSystem/formatCommandResult.ts
+++ b/packages/prompts/src/prompts/fileSystem/formatCommandResult.ts
@@ -28,8 +28,8 @@ export const formatCommandResult = ({
if (hasNonZeroExit) header += ` with exit code ${exitCode}`;
if (error) header += `: ${error}`;
parts.push(header);
- } else if (shellId) {
- parts.push(`Command started in background with shell_id: ${shellId}`);
+ } else if (exitCode === undefined) {
+ parts.push(`Command is still running after the wait window.\nshell_id: ${shellId}`);
} else {
parts.push('Command completed successfully.');
}
diff --git a/packages/tool-runtime/src/ComputerRuntime.ts b/packages/tool-runtime/src/ComputerRuntime.ts
index 5ba9cf0ede4..2f465daf510 100644
--- a/packages/tool-runtime/src/ComputerRuntime.ts
+++ b/packages/tool-runtime/src/ComputerRuntime.ts
@@ -350,6 +350,7 @@ export abstract class ComputerRuntime {
const outputSuccess = typeof r.success === 'boolean' ? r.success : result.success;
const state: GetCommandOutputState = {
+ durationMs: r.durationMs ?? r.duration_ms,
error: r.error,
exitCode: r.exitCode ?? r.exit_code,
newOutput: r.newOutput || r.output,
@@ -358,6 +359,7 @@ export abstract class ComputerRuntime {
};
const content = formatCommandOutput({
+ durationMs: r.durationMs ?? r.duration_ms,
error: r.error,
exitCode: r.exitCode ?? r.exit_code,
output: r.newOutput || r.output,
diff --git a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
index 7148b43a15a..8291927e2a5 100644
--- a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
+++ b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
@@ -186,6 +186,7 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {
case 'getCommandOutput': {
return {
result: {
+ durationMs: raw.duration_ms,
exitCode: raw.exit_code,
error: raw.error,
newOutput: raw.output,
diff --git a/packages/tool-runtime/src/types.ts b/packages/tool-runtime/src/types.ts
index a0e875ba802..70e951f0c0b 100644
--- a/packages/tool-runtime/src/types.ts
+++ b/packages/tool-runtime/src/types.ts
@@ -193,6 +193,7 @@ export interface RunCommandState {
}
export interface GetCommandOutputState {
+ durationMs?: number;
error?: string;
exitCode?: number;
newOutput?: string;