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(cli): preserve content/state for connect local file/shell tools (#15442)

Arvin Xu72ea0f94f79e
diff --git a/apps/cli/package.json b/apps/cli/package.json
index 9469654626a..7680d2c7bf6 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -33,6 +33,7 @@
"@lobechat/device-identity": "workspace:*",
"@lobechat/heterogeneous-agents": "workspace:*",
"@lobechat/local-file-shell": "workspace:*",
+ "@lobechat/tool-runtime": "workspace:*",
"@trpc/client": "^11.8.1",
"@types/node": "^22.13.5",
"@types/ws": "^8.18.1",
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index b833e1e49ec..d2bdbe1c808 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -280,6 +280,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
result: {
content: result.content,
error: result.error,
+ state: result.state,
success: result.success,
},
});
diff --git a/apps/cli/src/tools/index.test.ts b/apps/cli/src/tools/index.test.ts
index 61064b17d78..1b54301bda3 100644
--- a/apps/cli/src/tools/index.test.ts
+++ b/apps/cli/src/tools/index.test.ts
@@ -3,6 +3,7 @@ import { mkdir, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
+import { ShellProcessManager } from '@lobechat/local-file-shell';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { executeToolCall } from './index';
@@ -27,15 +28,17 @@ describe('executeToolCall', () => {
fs.rmSync(tmpDir, { force: true, recursive: true });
});
- it('should dispatch readFile', async () => {
+ it('should dispatch readFile with formatted content and structured state', async () => {
const filePath = path.join(tmpDir, 'test.txt');
await writeFile(filePath, 'hello world');
const result = await executeToolCall('readFile', JSON.stringify({ path: filePath }));
expect(result.success).toBe(true);
- const parsed = JSON.parse(result.content);
- expect(parsed.content).toContain('hello world');
+ // content is now the formatted prompt text, not raw JSON
+ expect(result.content).toContain('hello world');
+ // structured payload travels in `state` for client renders
+ expect((result.state as { content: string }).content).toContain('hello world');
});
it('should dispatch writeFile', async () => {
@@ -47,6 +50,7 @@ describe('executeToolCall', () => {
);
expect(result.success).toBe(true);
+ expect((result.state as { path: string }).path).toBe(filePath);
expect(fs.readFileSync(filePath, 'utf8')).toBe('written');
});
@@ -57,8 +61,7 @@ describe('executeToolCall', () => {
const result = await executeToolCall('readLocalFile', JSON.stringify({ path: filePath }));
expect(result.success).toBe(true);
- const parsed = JSON.parse(result.content);
- expect(parsed.content).toContain('legacy hello');
+ expect((result.state as { content: string }).content).toContain('legacy hello');
});
it('should dispatch runCommand', async () => {
@@ -68,8 +71,9 @@ describe('executeToolCall', () => {
);
expect(result.success).toBe(true);
- const parsed = JSON.parse(result.content);
- expect(parsed.stdout).toContain('dispatched');
+ expect(result.content).toContain('dispatched');
+ const state = result.state as { output?: string; stdout?: string };
+ expect(state.stdout ?? state.output).toContain('dispatched');
});
it('should dispatch listFiles', async () => {
@@ -78,8 +82,7 @@ describe('executeToolCall', () => {
const result = await executeToolCall('listFiles', JSON.stringify({ path: tmpDir }));
expect(result.success).toBe(true);
- const parsed = JSON.parse(result.content);
- expect(parsed.totalCount).toBeGreaterThan(0);
+ expect((result.state as { totalCount: number }).totalCount).toBeGreaterThan(0);
});
it('should dispatch globFiles', async () => {
@@ -91,8 +94,7 @@ describe('executeToolCall', () => {
);
expect(result.success).toBe(true);
- const parsed = JSON.parse(result.content);
- expect(parsed.files).toContain('test.ts');
+ expect((result.state as { files: string[] }).files).toContain('test.ts');
});
it('should dispatch editFile', async () => {
@@ -109,6 +111,7 @@ describe('executeToolCall', () => {
);
expect(result.success).toBe(true);
+ expect((result.state as { replacements: number }).replacements).toBeGreaterThan(0);
expect(fs.readFileSync(filePath, 'utf8')).toBe('new content');
});
@@ -119,19 +122,15 @@ describe('executeToolCall', () => {
expect(result.error).toContain('Unknown tool API');
});
- it('should handle tool that returns a string result', async () => {
- // runCommand returns an object, but we test the string branch by mocking
- // Actually, none of the tools return plain strings, so the JSON.stringify branch
- // is always taken. The string check is for future-proofing.
- // Let's verify the JSON output path
+ it('should carry structured state on file reads', async () => {
const filePath = path.join(tmpDir, 'str.txt');
await writeFile(filePath, 'content');
const result = await executeToolCall('readFile', JSON.stringify({ path: filePath }));
expect(result.success).toBe(true);
- // Result should be valid JSON
- expect(() => JSON.parse(result.content)).not.toThrow();
+ expect(result.state).toBeDefined();
+ expect(typeof result.content).toBe('string');
});
it('should return error for invalid JSON arguments', async () => {
@@ -150,6 +149,7 @@ describe('executeToolCall', () => {
);
expect(result.success).toBe(true);
+ expect(result.state).toBeDefined();
});
it('should dispatch searchFiles', async () => {
@@ -161,6 +161,7 @@ describe('executeToolCall', () => {
);
expect(result.success).toBe(true);
+ expect(result.state).toBeDefined();
});
it('should dispatch getCommandOutput', async () => {
@@ -169,9 +170,21 @@ describe('executeToolCall', () => {
JSON.stringify({ shell_id: 'nonexistent' }),
);
+ // The runtime envelopes a failed lookup as success:true with the failure in state
expect(result.success).toBe(true);
- const parsed = JSON.parse(result.content);
- expect(parsed.success).toBe(false);
+ expect((result.state as { success: boolean }).success).toBe(false);
+ });
+
+ it('should forward the gateway timeout to getCommandOutput polling', async () => {
+ const spy = vi
+ .spyOn(ShellProcessManager.prototype, 'getOutput')
+ .mockResolvedValue({ exit_code: 0, output: '', stderr: '', stdout: '', success: true });
+
+ // 3rd arg is the gateway per-call timeout; executeToolCall injects it into args
+ await executeToolCall('getCommandOutput', JSON.stringify({ shell_id: 'sid' }), 5000);
+
+ expect(spy).toHaveBeenCalledWith(expect.objectContaining({ shell_id: 'sid', timeout: 5000 }));
+ spy.mockRestore();
});
it('should dispatch killCommand', async () => {
@@ -181,7 +194,6 @@ describe('executeToolCall', () => {
);
expect(result.success).toBe(true);
- const parsed = JSON.parse(result.content);
- expect(parsed.success).toBe(false);
+ expect((result.state as { success: boolean }).success).toBe(false);
});
});
diff --git a/apps/cli/src/tools/index.ts b/apps/cli/src/tools/index.ts
index e6ebbf43999..60d11813141 100644
--- a/apps/cli/src/tools/index.ts
+++ b/apps/cli/src/tools/index.ts
@@ -1,41 +1,19 @@
import { log } from '../utils/logger';
import { checkPlatformCapability } from './checkPlatformCapability';
-import {
- editLocalFile,
- globLocalFiles,
- grepContent,
- listLocalFiles,
- readLocalFile,
- searchLocalFiles,
- writeLocalFile,
-} from './file';
import { getAgentProfile } from './getAgentProfile';
import { cancelHeteroTask, runHeteroTask } from './heteroTask';
-import { getCommandOutput, killCommand, runCommand } from './shell';
+import { runLocalSystemTool } from './localSystemRuntime';
+/**
+ * CLI-only tools (platform agents). File/shell tools are handled separately by
+ * {@link runLocalSystemTool}, which routes them through
+ * `LocalSystemExecutionRuntime` so the result carries structured `state`.
+ */
const methodMap: Record<string, (args: any) => Promise<unknown>> = {
cancelHeteroTask,
checkPlatformCapability,
getAgentProfile,
- editFile: editLocalFile,
- getCommandOutput,
- globFiles: globLocalFiles,
- grepContent,
- killCommand,
- listFiles: listLocalFiles,
- readFile: readLocalFile,
- runCommand,
runHeteroTask,
- searchFiles: searchLocalFiles,
- writeFile: writeLocalFile,
-
- // Legacy aliases β€” older Gateway versions may still send the long form
- editLocalFile,
- globLocalFiles,
- listLocalFiles,
- readLocalFile,
- searchLocalFiles,
- writeLocalFile,
};
export async function executeToolCall(
@@ -45,19 +23,44 @@ export async function executeToolCall(
): Promise<{
content: string;
error?: string;
+ state?: unknown;
success: boolean;
}> {
- const handler = methodMap[apiName];
- if (!handler) {
- return { content: '', error: `Unknown tool API: ${apiName}`, success: false };
+ let args: Record<string, any>;
+ try {
+ args = JSON.parse(argsStr);
+ } catch (error) {
+ const errorMsg = error instanceof Error ? error.message : String(error);
+ log.error(`Tool call failed: ${apiName} - ${errorMsg}`);
+ return { content: '', error: errorMsg, success: false };
}
+ const finalArgs =
+ typeof timeout === 'number' && Number.isFinite(timeout) && !('timeout' in args)
+ ? { ...args, timeout }
+ : args;
+
try {
- const args = JSON.parse(argsStr);
- const finalArgs =
- typeof timeout === 'number' && Number.isFinite(timeout) && !('timeout' in args)
- ? { ...args, timeout }
- : args;
+ // File/shell tools route through LocalSystemExecutionRuntime so `content` is
+ // the formatted prompt text and `state` carries the structured payload for
+ // client renders β€” matching the desktop gateway path (PR #15114).
+ const localResult = await runLocalSystemTool(apiName, finalArgs);
+ if (localResult) {
+ const { error } = localResult;
+ return {
+ content: localResult.content,
+ error:
+ error instanceof Error ? error.message : typeof error === 'string' ? error : undefined,
+ state: localResult.state,
+ success: localResult.success,
+ };
+ }
+
+ // CLI-only tools return raw domain payloads, serialized into `content`.
+ const handler = methodMap[apiName];
+ if (!handler) {
+ return { content: '', error: `Unknown tool API: ${apiName}`, success: false };
+ }
const result = await handler(finalArgs);
const content = typeof result === 'string' ? result : JSON.stringify(result);
diff --git a/apps/cli/src/tools/localSystemRuntime.ts b/apps/cli/src/tools/localSystemRuntime.ts
new file mode 100644
index 00000000000..2cba9f70c0e
--- /dev/null
+++ b/apps/cli/src/tools/localSystemRuntime.ts
@@ -0,0 +1,197 @@
+import path from 'node:path';
+
+import type {
+ EditFileParams,
+ GetCommandOutputParams,
+ GlobFilesParams,
+ GrepContentParams,
+ KillCommandParams,
+ ListFilesParams,
+ ReadFileParams,
+ RunCommandParams,
+ SearchFilesParams,
+ WriteFileParams,
+} from '@lobechat/local-file-shell';
+import { type ILocalSystemService, LocalSystemExecutionRuntime } from '@lobechat/tool-runtime';
+
+import {
+ editLocalFile,
+ globLocalFiles,
+ grepContent,
+ listLocalFiles,
+ readLocalFile,
+ searchLocalFiles,
+ writeLocalFile,
+} from './file';
+import { getCommandOutput, killCommand, runCommand } from './shell';
+
+/**
+ * Output envelope produced by {@link runLocalSystemTool}. Mirrors
+ * `@lobechat/types`' `BuiltinServerRuntimeOutput`: `content` is the formatted
+ * prompt text fed to the LLM, while `state` carries the structured payload that
+ * client renders consume as `pluginState`.
+ */
+export interface LocalSystemToolOutput {
+ content: string;
+ error?: unknown;
+ state?: unknown;
+ success: boolean;
+}
+
+/**
+ * Stub for `ILocalSystemService` methods the CLI does not expose (batch read,
+ * move, rename). These are never routed by {@link runLocalSystemTool}; the
+ * interface just requires them, so we fail loudly if one is ever reached.
+ */
+const unsupported = (method: string) => (): Promise<never> =>
+ Promise.reject(new Error(`${method} is not supported by the LobeHub CLI`));
+
+/**
+ * Adapter wiring the CLI's `@lobechat/local-file-shell` functions (file ops) and
+ * shell wrappers (with the shared `ShellProcessManager`) into the shape the
+ * runtime expects. The runtime denormalizes its camelCase params back to the
+ * snake_case IPC shapes these functions consume β€” see `LocalSystemExecutionRuntime`.
+ */
+const localSystemService: ILocalSystemService = {
+ editLocalFile,
+ getCommandOutput,
+ globFiles: globLocalFiles,
+ grepContent,
+ killCommand,
+ listLocalFiles,
+ moveLocalFiles: unsupported('moveLocalFiles'),
+ readLocalFile,
+ readLocalFiles: unsupported('readLocalFiles'),
+ renameLocalFile: unsupported('renameLocalFile'),
+ runCommand,
+ searchLocalFiles,
+ writeFile: writeLocalFile,
+};
+
+const runtime = new LocalSystemExecutionRuntime(localSystemService);
+
+/**
+ * Legacy API name aliases used by older gateway versions. Normalized to the
+ * current tool names before dispatch.
+ */
+const LEGACY_API_ALIASES: Record<string, string> = {
+ editLocalFile: 'editFile',
+ globLocalFiles: 'globFiles',
+ listLocalFiles: 'listFiles',
+ readLocalFile: 'readFile',
+ searchLocalFiles: 'searchFiles',
+ writeLocalFile: 'writeFile',
+};
+
+/**
+ * Resolve a relative path against a scope (CWD). Mirrors the desktop gateway's
+ * inline copy of the renderer-side `resolveArgsWithScope` helper so the CLI and
+ * desktop produce identical scoping for search/grep tools.
+ */
+const resolveArgsWithScope = <T extends { scope?: string }>(args: T, pathField: string): T => {
+ const scope = args.scope;
+ const bag = args as Record<PropertyKey, unknown>;
+ const currentPath = typeof bag[pathField] === 'string' ? (bag[pathField] as string) : undefined;
+ if (!scope) return args;
+ if (!currentPath) return { ...args, [pathField]: scope };
+ if (path.isAbsolute(currentPath)) return args;
+ return { ...args, [pathField]: path.join(scope, currentPath) };
+};
+
+/**
+ * Route file/shell tool calls through `LocalSystemExecutionRuntime` so the
+ * result carries structured `state` (for client renders) and `content` is the
+ * formatted prompt text β€” matching the desktop gateway path (PR #15114).
+ *
+ * Returns `null` when `apiName` is not a local-system tool, so the caller can
+ * fall back to CLI-only tools (platform agents).
+ */
+export async function runLocalSystemTool(
+ apiName: string,
+ args: Record<string, any>,
+): Promise<LocalSystemToolOutput | null> {
+ const normalized = LEGACY_API_ALIASES[apiName] ?? apiName;
+
+ switch (normalized) {
+ case 'listFiles': {
+ const p = args as ListFilesParams;
+ return runtime.listFiles({
+ directoryPath: p.path,
+ limit: p.limit,
+ sortBy: p.sortBy,
+ sortOrder: p.sortOrder,
+ } as never);
+ }
+
+ case 'readFile': {
+ const p = args as ReadFileParams;
+ return runtime.readFile({
+ endLine: p.loc?.[1],
+ path: p.path,
+ startLine: p.loc?.[0],
+ });
+ }
+
+ case 'writeFile': {
+ return runtime.writeFile(args as WriteFileParams);
+ }
+
+ case 'editFile': {
+ const p = args as EditFileParams;
+ return runtime.editFile({
+ all: p.replace_all,
+ path: p.file_path,
+ replace: p.new_string,
+ search: p.old_string,
+ });
+ }
+
+ case 'searchFiles': {
+ const resolved = resolveArgsWithScope(
+ args as SearchFilesParams & { scope?: string },
+ 'directory',
+ );
+ return runtime.searchFiles({ ...resolved, directory: resolved.directory || '' } as never);
+ }
+
+ case 'grepContent': {
+ const resolved = resolveArgsWithScope(args as GrepContentParams, 'path');
+ return runtime.grepContent(resolved as never);
+ }
+
+ case 'globFiles': {
+ const p = args as GlobFilesParams;
+ // Honor both `scope` (current manifest) and the `cwd` legacy alias.
+ return runtime.globFiles({ directory: p.scope ?? p.cwd, pattern: p.pattern });
+ }
+
+ case 'runCommand': {
+ // ComputerRuntime's RunCommandState reads `args.background`; the manifest
+ // exposes `run_in_background`. Without this normalize the state would
+ // always show foreground even for background commands.
+ const p = args as RunCommandParams;
+ return runtime.runCommand({ ...p, background: p.run_in_background } as never);
+ }
+
+ case 'getCommandOutput': {
+ // Forward `timeout` (gateway per-call budget, injected into args by
+ // executeToolCall) so polling a running command honors it instead of the
+ // service's default wait. The runtime carries it through to getOutput.
+ const p = args as GetCommandOutputParams;
+ return runtime.getCommandOutput({
+ commandId: p.shell_id,
+ filter: p.filter,
+ timeout: p.timeout,
+ } as never);
+ }
+
+ case 'killCommand': {
+ const p = args as KillCommandParams;
+ return runtime.killCommand({ commandId: p.shell_id });
+ }
+
+ default: {
+ return null;
+ }
+ }
+}
diff --git a/apps/cli/tsconfig.json b/apps/cli/tsconfig.json
index 57b3ffbcb8a..cf71e953761 100644
--- a/apps/cli/tsconfig.json
+++ b/apps/cli/tsconfig.json
@@ -15,6 +15,7 @@
"paths": {
"@lobechat/device-gateway-client": ["../../packages/device-gateway-client/src"],
"@lobechat/local-file-shell": ["../../packages/local-file-shell/src"],
+ "@lobechat/tool-runtime": ["../../packages/tool-runtime/src"],
"@/*": ["../../src/*"]
}
},
diff --git a/apps/cli/vitest.config.mts b/apps/cli/vitest.config.mts
index f029b5f9e27..99caf63e150 100644
--- a/apps/cli/vitest.config.mts
+++ b/apps/cli/vitest.config.mts
@@ -17,6 +17,10 @@ export default defineConfig({
find: '@lobechat/file-loaders',
replacement: path.resolve(__dirname, '../../packages/file-loaders/src/index.ts'),
},
+ {
+ find: '@lobechat/tool-runtime',
+ replacement: path.resolve(__dirname, '../../packages/tool-runtime/src/index.ts'),
+ },
],
},
test: {
diff --git a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
index ec208f8d3c0..7148b43a15a 100644
--- a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
+++ b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
@@ -115,7 +115,7 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {
}
case 'getCommandOutput': {
- return { filter: params.filter, shell_id: params.commandId };
+ return { filter: params.filter, shell_id: params.commandId, timeout: params.timeout };
}
case 'killCommand': {
diff --git a/packages/tool-runtime/src/types.ts b/packages/tool-runtime/src/types.ts
index 4827f00c0a7..246bf3216d9 100644
--- a/packages/tool-runtime/src/types.ts
+++ b/packages/tool-runtime/src/types.ts
@@ -82,6 +82,12 @@ export interface RunCommandParams {
export interface GetCommandOutputParams {
commandId: string;
+ /**
+ * Max time to wait for this observation before returning (does not kill the
+ * process). Forwarded to the service so callers polling a running command can
+ * honor a per-call/gateway budget instead of the service's default wait.
+ */
+ timeout?: number;
}
export interface KillCommandParams {