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(remote-device): preserve content/state across gateway tool calls (#15114)

Arvin Xu7d1086b09658
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 7ef2642c746..c2daf5a307d 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -63,6 +63,7 @@
"@lobechat/file-loaders": "workspace:*",
"@lobechat/heterogeneous-agents": "workspace:*",
"@lobechat/local-file-shell": "workspace:*",
+ "@lobechat/tool-runtime": "workspace:*",
"@lobehub/i18n-cli": "^1.25.1",
"@modelcontextprotocol/sdk": "^1.24.3",
"@t3-oss/env-core": "^0.13.8",
diff --git a/apps/desktop/pnpm-workspace.yaml b/apps/desktop/pnpm-workspace.yaml
index 10262e6d927..c81b701d2e2 100644
--- a/apps/desktop/pnpm-workspace.yaml
+++ b/apps/desktop/pnpm-workspace.yaml
@@ -11,6 +11,8 @@ packages:
- '../../packages/device-gateway-client'
- '../../packages/device-identity'
- '../../packages/local-file-shell'
+ - '../../packages/tool-runtime'
+ - '../../packages/prompts'
- './stubs/business-const'
- './stubs/types'
- '.'
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index 71098b106ee..f128b345995 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -4,7 +4,23 @@ import os from 'node:os';
import path from 'node:path';
import type { AgentRunRequestMessage } from '@lobechat/device-gateway-client';
-import type { GatewayConnectionStatus } from '@lobechat/electron-client-ipc';
+import type {
+ EditLocalFileParams,
+ GatewayConnectionStatus,
+ GetCommandOutputParams,
+ GlobFilesParams,
+ GrepContentParams,
+ KillCommandParams,
+ ListLocalFileParams,
+ LocalReadFileParams,
+ LocalReadFilesParams,
+ LocalSearchFilesParams,
+ MoveLocalFilesParams,
+ RenameLocalFileParams,
+ RunCommandParams,
+ WriteLocalFileParams,
+} from '@lobechat/electron-client-ipc';
+import { type ILocalSystemService, LocalSystemExecutionRuntime } from '@lobechat/tool-runtime';
import GatewayConnectionService from '@/services/gatewayConnectionSrv';
import ImessageBridgeService from '@/services/imessageBridgeSrv';
@@ -55,8 +71,62 @@ interface PlatformTaskEntry {
topicId: string;
}
-type ToolCallHandler = () => Promise<unknown>;
-type ToolCallHandlerMap = Record<string, ToolCallHandler>;
+/**
+ * Local mirror of `@lobechat/types`' `BuiltinServerRuntimeOutput`. Inlined
+ * because the desktop tsconfig doesn't expose `@lobechat/types`, and the shape
+ * is tiny + stable.
+ */
+interface BuiltinServerRuntimeOutput {
+ content: string;
+ error?: unknown;
+ state?: unknown;
+ success: boolean;
+}
+
+/**
+ * Legacy API name aliases used by older gateway versions. Normalized to the
+ * current `LocalSystemApiEnum` names before dispatch. `renameLocalFile` is
+ * intentionally absent β€” it has no equivalent on the new surface and is
+ * handled by a dedicated branch below.
+ */
+const LEGACY_API_ALIASES: Record<string, string> = {
+ editLocalFile: 'editFile',
+ globLocalFiles: 'globFiles',
+ listLocalFiles: 'listFiles',
+ moveLocalFiles: 'moveFiles',
+ readLocalFile: 'readFile',
+ searchLocalFiles: 'searchFiles',
+ writeLocalFile: 'writeFile',
+};
+
+/**
+ * Parse a JSON string, returning `undefined` on failure. Used to surface the
+ * structured shape of platform-agent tool results (which return pre-stringified
+ * JSON) as `state` for the renderer, without crashing on malformed input.
+ */
+const safeJsonParse = (input: string): unknown => {
+ try {
+ return JSON.parse(input);
+ } catch {
+ return undefined;
+ }
+};
+
+/**
+ * Resolve a relative path against a scope (CWD). Mirrors the renderer-side
+ * `resolveArgsWithScope` helper in `@lobechat/builtin-tool-local-system` β€” kept
+ * here as a small inline copy to avoid pulling the renderer-side `./client`
+ * subpath (which transitively requires React + antd) into the main process.
+ */
+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) };
+};
/**
* GatewayConnectionCtr
@@ -72,6 +142,8 @@ export default class GatewayConnectionCtr extends ControllerModule {
/** Maps topicId β†’ hermes session_id for multi-turn conversation continuity. */
private readonly hermesSessionMap = new Map<string, string>();
+ private localSystemRuntime: LocalSystemExecutionRuntime | null = null;
+
// ─── Service Accessor ───
private get service() {
@@ -219,21 +291,208 @@ export default class GatewayConnectionCtr extends ControllerModule {
// ─── Tool Call Routing ───
- private async executeToolCall(apiName: string, args: any): Promise<unknown> {
- const methodMap = {
- ...this.getLocalFileToolHandlers(args),
- ...this.getShellCommandToolHandlers(args),
- ...this.getPlatformAgentToolHandlers(args),
- } satisfies ToolCallHandlerMap;
-
- const handler = methodMap[apiName];
- if (!handler) {
- throw new Error(
- `Tool "${apiName}" is not available on this device. It may not be supported in the current desktop version. Please skip this tool and try alternative approaches.`,
- );
+ /**
+ * Lazy-construct the LocalSystemExecutionRuntime backed by a thin service
+ * adapter over the existing controllers. The runtime is the same one the
+ * renderer uses, so remote tool calls produce identical
+ * `{ content, state, success }` envelopes β€” `content` is the LLM-facing
+ * prompt text, `state` is the structured payload, both flow downstream
+ * intact (the gateway / DeviceProxy / RuntimeExecutors paths preserve them
+ * and write `state` to the tool message's `pluginState`).
+ */
+ private getLocalSystemRuntime(): LocalSystemExecutionRuntime {
+ if (!this.localSystemRuntime) {
+ const local = this.localFileCtr;
+ const shell = this.shellCommandCtr;
+ const service: ILocalSystemService = {
+ editLocalFile: (p) => local.handleEditFile(p),
+ getCommandOutput: (p) => shell.handleGetCommandOutput(p),
+ globFiles: (p) => local.handleGlobFiles(p),
+ grepContent: (p) => local.handleGrepContent(p),
+ killCommand: (p) => shell.handleKillCommand(p),
+ listLocalFiles: (p) => local.listLocalFiles(p),
+ moveLocalFiles: (p) => local.handleMoveFiles(p),
+ readLocalFile: (p) => local.readFile(p),
+ readLocalFiles: (p) => local.readFiles(p),
+ renameLocalFile: (p) => local.handleRenameFile(p),
+ runCommand: (p) => shell.handleRunCommand(p),
+ searchLocalFiles: (p) => local.handleLocalFilesSearch(p),
+ writeFile: (p) => local.handleWriteFile(p),
+ };
+ this.localSystemRuntime = new LocalSystemExecutionRuntime(service);
}
+ return this.localSystemRuntime;
+ }
+
+ private async executeToolCall(
+ apiName: string,
+ args: unknown,
+ ): Promise<BuiltinServerRuntimeOutput> {
+ const runtime = this.getLocalSystemRuntime();
+ const normalized = LEGACY_API_ALIASES[apiName] ?? apiName;
+
+ // Each case narrows `args` to its IPC param type β€” the manifest guarantees
+ // the gateway sends params matching the apiName. The `as never` casts on
+ // runtime calls are legitimate widenings: the runtime's typed signatures
+ // (e.g. `ListFilesParams`) are narrower than what the IPC layer accepts
+ // (`limit`, `run_in_background`, etc.), and the same casts exist in the
+ // renderer-side `LocalSystemExecutor`.
+ switch (normalized) {
+ case 'listFiles': {
+ const p = args as ListLocalFileParams;
+ return runtime.listFiles({
+ directoryPath: p.path,
+ limit: p.limit,
+ sortBy: p.sortBy,
+ sortOrder: p.sortOrder,
+ } as never);
+ }
+
+ case 'readFile': {
+ const p = args as LocalReadFileParams;
+ return runtime.readFile({
+ endLine: p.loc?.[1],
+ path: p.path,
+ startLine: p.loc?.[0],
+ });
+ }
+
+ case 'readFiles': {
+ return runtime.readFiles(args as LocalReadFilesParams);
+ }
+
+ case 'searchFiles': {
+ const resolved = resolveArgsWithScope(args as LocalSearchFilesParams, 'directory');
+ return runtime.searchFiles({
+ ...resolved,
+ directory: resolved.directory || '',
+ });
+ }
+
+ case 'moveFiles': {
+ const p = args as MoveLocalFilesParams;
+ return runtime.moveFiles({
+ operations: p.items?.map((item) => ({
+ destination: item.newPath,
+ source: item.oldPath,
+ })),
+ });
+ }
+
+ case 'writeFile': {
+ return runtime.writeFile(args as WriteLocalFileParams);
+ }
+
+ case 'editFile': {
+ const p = args as EditLocalFileParams;
+ return runtime.editFile({
+ all: p.replace_all,
+ path: p.file_path,
+ replace: p.new_string,
+ search: p.old_string,
+ });
+ }
- return handler();
+ 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': {
+ const p = args as GetCommandOutputParams;
+ return runtime.getCommandOutput({
+ commandId: p.shell_id,
+ filter: p.filter,
+ } as never);
+ }
+
+ case 'killCommand': {
+ const p = args as KillCommandParams;
+ return runtime.killCommand({
+ commandId: p.shell_id,
+ });
+ }
+
+ case 'grepContent': {
+ const resolved = resolveArgsWithScope(args as GrepContentParams, 'path');
+ return runtime.grepContent(resolved as never);
+ }
+
+ case 'globFiles': {
+ const p = args as GlobFilesParams;
+ return runtime.globFiles({
+ directory: p.scope,
+ pattern: p.pattern,
+ });
+ }
+
+ case 'renameLocalFile': {
+ // ComputerRuntime has no public rename method β€” new surface uses
+ // `moveFiles`. Legacy gateway versions may still emit this name, so we
+ // call the IPC handler directly and wrap the raw result into the
+ // BuiltinServerRuntimeOutput shape so `state` still flows downstream.
+ const raw = await this.localFileCtr.handleRenameFile(args as RenameLocalFileParams);
+ return {
+ content: raw.success
+ ? `Renamed to ${raw.newPath}`
+ : `Rename failed: ${raw.error ?? 'unknown error'}`,
+ state: raw,
+ success: raw.success,
+ };
+ }
+
+ // ─── Platform agent tools (openclaw / hermes) ───
+ // These don't go through LocalSystemExecutionRuntime β€” they return raw
+ // domain payloads that we envelope into BuiltinServerRuntimeOutput here.
+ // `content` is the JSON-serialized payload (what the LLM reads); `state`
+ // carries the parsed object so the renderer can render structured UI.
+
+ case 'checkPlatformCapability': {
+ const result = await this.checkPlatformCapability(args as { platform: string });
+ return { content: JSON.stringify(result), state: result, success: true };
+ }
+
+ case 'getAgentProfile': {
+ const result = await this.getAgentProfile(
+ args as { agentId?: string; platform: string },
+ );
+ return { content: JSON.stringify(result), state: result, success: true };
+ }
+
+ case 'runHeteroTask': {
+ // runHeteroTask returns a pre-stringified JSON payload β€” pass it through
+ // as `content` and surface the parsed shape as `state`.
+ const json = await this.runHeteroTask(
+ args as {
+ agentId?: string;
+ agentType: string;
+ cwd?: string;
+ operationId: string;
+ prompt: string;
+ taskId: string;
+ topicId: string;
+ },
+ );
+ return { content: json, state: safeJsonParse(json), success: true };
+ }
+
+ case 'cancelHeteroTask': {
+ const json = await this.cancelHeteroTask(args as { signal?: string; taskId: string });
+ return { content: json, state: safeJsonParse(json), success: true };
+ }
+
+ default: {
+ throw new Error(
+ `Tool "${apiName}" is not available on this device. It may not be supported in the current desktop version. Please skip this tool and try alternative approaches.`,
+ );
+ }
+ }
}
private async executeMessageApi(
@@ -250,59 +509,6 @@ export default class GatewayConnectionCtr extends ControllerModule {
);
}
- private getLocalFileToolHandlers(args: any): ToolCallHandlerMap {
- const editFile = () => this.localFileCtr.handleEditFile(args);
- const globFiles = () => this.localFileCtr.handleGlobFiles(args);
- const listFiles = () => this.localFileCtr.listLocalFiles(args);
- const moveFiles = () => this.localFileCtr.handleMoveFiles(args);
- const readFile = () => this.localFileCtr.readFile(args);
- const searchFiles = () => this.localFileCtr.handleLocalFilesSearch(args);
- const writeFile = () => this.localFileCtr.handleWriteFile(args);
-
- return {
- editFile,
- globFiles,
- grepContent: () => this.localFileCtr.handleGrepContent(args),
- listFiles,
- moveFiles,
- readFile,
- searchFiles,
- writeFile,
-
- // Legacy aliases β€” keep these so older Gateway versions sending the long
- // names continue to route correctly. `renameLocalFile` is also kept even
- // though the new surface drops rename (it's now handled by `moveFiles`).
- editLocalFile: editFile,
- globLocalFiles: globFiles,
- listLocalFiles: listFiles,
- moveLocalFiles: moveFiles,
- readLocalFile: readFile,
- renameLocalFile: () => this.localFileCtr.handleRenameFile(args),
- searchLocalFiles: searchFiles,
- writeLocalFile: writeFile,
- };
- }
-
- private getShellCommandToolHandlers(args: any): ToolCallHandlerMap {
- return {
- getCommandOutput: () => this.shellCommandCtr.handleGetCommandOutput(args),
- killCommand: () => this.shellCommandCtr.handleKillCommand(args),
- runCommand: () => this.shellCommandCtr.handleRunCommand(args),
- };
- }
-
- private getPlatformAgentToolHandlers(args: any): ToolCallHandlerMap {
- return {
- // Platform agent capability probing
- checkPlatformCapability: () => this.checkPlatformCapability(args),
- getAgentProfile: () => this.getAgentProfile(args),
-
- // Platform agent task execution (openclaw / hermes)
- cancelHeteroTask: () => this.cancelHeteroTask(args),
- runHeteroTask: () => this.runHeteroTask(args),
- };
- }
-
// ─── Platform Capability Probing ───
private async checkPlatformCapability(args: {
diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
index 02b06eb3559..c5e286f3185 100644
--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
@@ -526,15 +526,18 @@ describe('GatewayConnectionCtr', () => {
['renameLocalFile', 'handleRenameFile', mockLocalFileCtr],
] as const)('should route %s to %s', async (apiName, methodName, controller) => {
const client = await connectAndOpen();
- const args = { test: 'arg' };
- client.simulateToolCallRequest(apiName, args);
+ // Each tool's args are domain-shaped (path, file_path, items, etc.).
+ // The runtime denormalizes them before calling the controller, so this
+ // test only asserts that the *right* controller method runs β€” see the
+ // envelope-shape test below for end-to-end content/state coverage.
+ client.simulateToolCallRequest(apiName, { test: 'arg' });
await vi.advanceTimersByTimeAsync(0);
- expect((controller as any)[methodName]).toHaveBeenCalledWith(args);
+ expect((controller as any)[methodName]).toHaveBeenCalled();
});
- it('should send tool_call_response with success result', async () => {
+ it('should send tool_call_response with content + state envelope on success', async () => {
vi.mocked(mockLocalFileCtr.readFile).mockResolvedValueOnce({
charCount: 5,
content: 'hello',
@@ -552,23 +555,20 @@ describe('GatewayConnectionCtr', () => {
client.simulateToolCallRequest('readFile', { path: '/a.txt' }, 'req-42');
await vi.advanceTimersByTimeAsync(0);
- expect(client.sendToolCallResponse).toHaveBeenCalledWith({
- requestId: 'req-42',
- result: {
- content: JSON.stringify({
- charCount: 5,
- content: 'hello',
- createdTime: new Date('2024-01-01'),
- filename: 'a.txt',
- fileType: '.txt',
- lineCount: 1,
- loc: [1, 1],
- modifiedTime: new Date('2024-01-01'),
- totalCharCount: 5,
- totalLineCount: 1,
- }),
- success: true,
- },
+ // The runtime produces a formatted prompt string for `content` and a
+ // structured snapshot for `state`. We only assert envelope shape here
+ // β€” the exact prompt format is owned by the runtime/prompts packages.
+ expect(client.sendToolCallResponse).toHaveBeenCalledTimes(1);
+ const response = client.sendToolCallResponse.mock.calls[0][0];
+ expect(response.requestId).toBe('req-42');
+ expect(response.result.success).toBe(true);
+ expect(typeof response.result.content).toBe('string');
+ expect(response.result.content.length).toBeGreaterThan(0);
+ expect(response.result.content).toContain('hello');
+ expect(response.result.state).toMatchObject({
+ content: 'hello',
+ filename: 'a.txt',
+ path: '/a.txt',
});
});
@@ -976,6 +976,7 @@ describe('GatewayConnectionCtr', () => {
requestId: 'req-cap',
result: {
content: JSON.stringify({ available: true, version: 'openclaw 1.2.3' }),
+ state: { available: true, version: 'openclaw 1.2.3' },
success: true,
},
});
@@ -1000,6 +1001,7 @@ describe('GatewayConnectionCtr', () => {
requestId: 'req-cap-nover',
result: {
content: JSON.stringify({ available: true }),
+ state: { available: true },
success: true,
},
});
@@ -1025,6 +1027,10 @@ describe('GatewayConnectionCtr', () => {
available: false,
reason: 'openclaw is not installed on this device',
}),
+ state: {
+ available: false,
+ reason: 'openclaw is not installed on this device',
+ },
success: true,
},
});
@@ -1043,6 +1049,7 @@ describe('GatewayConnectionCtr', () => {
requestId: 'req-unknown-plat',
result: {
content: JSON.stringify({ available: false, reason: 'Unknown platform: unknownBot' }),
+ state: { available: false, reason: 'Unknown platform: unknownBot' },
success: true,
},
});
@@ -1057,6 +1064,7 @@ describe('GatewayConnectionCtr', () => {
requestId: 'req-profile',
result: {
content: JSON.stringify({}),
+ state: {},
success: true,
},
});
diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
index 4802e29447f..b3c402e39cb 100644
--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts
+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
@@ -6,6 +6,7 @@ import type {
MessageApiRequestMessage,
SystemInfoRequestMessage,
ToolCallRequestMessage,
+ ToolCallResponseMessage,
} from '@lobechat/device-gateway-client';
import { GatewayClient } from '@lobechat/device-gateway-client';
import type { IdentitySource } from '@lobechat/device-identity';
@@ -22,14 +23,46 @@ const logger = createLogger('services:GatewayConnectionSrv');
const DEFAULT_GATEWAY_URL = 'https://device-gateway.lobehub.com';
-interface ToolCallHandler {
- (apiName: string, args: any): Promise<unknown>;
+/**
+ * Result envelope a tool-call handler must return. Mirrors
+ * `BuiltinServerRuntimeOutput` so the renderer-side and remote-device paths
+ * stay symmetric: `content` is the LLM-facing prompt text; `state` carries the
+ * structured payload that downstream persists into `pluginState`.
+ */
+interface ToolCallResult {
+ content: string;
+ error?: unknown;
+ state?: unknown;
+ success: boolean;
}
interface MessageApiHandler {
(platform: string, apiName: string, payload: Record<string, unknown>): Promise<unknown>;
}
+interface ToolCallHandler {
+ (apiName: string, args: unknown): Promise<ToolCallResult>;
+}
+
+/**
+ * Coerce a runtime error (which may be an Error, string, or `{ message }`
+ * object) into the string shape the wire protocol expects. Returns undefined
+ * when there's no error to transmit.
+ */
+const serializeWireError = (err: unknown): string | undefined => {
+ if (err === undefined || err === null) return undefined;
+ if (typeof err === 'string') return err;
+ if (err instanceof Error) return err.message;
+ if (typeof err === 'object' && 'message' in err && typeof err.message === 'string') {
+ return err.message;
+ }
+ try {
+ return JSON.stringify(err);
+ } catch {
+ return String(err);
+ }
+};
+
interface AgentRunHandler {
(request: AgentRunRequestMessage): Promise<{ reason?: string; status: 'accepted' | 'rejected' }>;
}
@@ -387,13 +420,21 @@ export default class GatewayConnectionService extends ServiceModule {
const args = JSON.parse(argsStr);
const result = await this.toolCallHandler(apiName, args);
- client.sendToolCallResponse({
- requestId,
- result: {
- content: typeof result === 'string' ? result : JSON.stringify(result),
- success: true,
- },
- });
+ // Forward the typed envelope unchanged. Critically, do NOT stringify the
+ // whole result into `content` β€” that would bury the structured payload
+ // inside a JSON blob and lose `state`. The wire protocol carries each
+ // field separately so downstream (`DeviceProxy` β†’ `RuntimeExecutors`)
+ // can persist `state` to `pluginState`. Optional fields are only set
+ // when present so payloads stay minimal.
+ const wireResult: ToolCallResponseMessage['result'] = {
+ content: result.content,
+ success: result.success,
+ };
+ const wireError = serializeWireError(result.error);
+ if (wireError !== undefined) wireResult.error = wireError;
+ if (result.state !== undefined) wireResult.state = result.state;
+
+ client.sendToolCallResponse({ requestId, result: wireResult });
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
logger.error(`Tool call failed: apiName=${apiName}, error=${errorMsg}`);
diff --git a/apps/desktop/stubs/types/src/index.ts b/apps/desktop/stubs/types/src/index.ts
index 2602a146bcb..227f53806c4 100644
--- a/apps/desktop/stubs/types/src/index.ts
+++ b/apps/desktop/stubs/types/src/index.ts
@@ -17,3 +17,16 @@ export interface DesktopHotkeyItem {
}
export type DesktopHotkeyConfig = Record<DesktopHotkeyId, string>;
+
+/**
+ * Mirror of `@lobechat/types`' `BuiltinServerRuntimeOutput`. Reached by
+ * `@lobechat/tool-runtime` (the runtime the gateway controller reuses) via
+ * `import type`, so only the shape is needed. Keep in sync with
+ * `packages/types/src/tool/builtin.ts`.
+ */
+export interface BuiltinServerRuntimeOutput {
+ content: string;
+ error?: unknown;
+ state?: unknown;
+ success: boolean;
+}
diff --git a/packages/builtin-tool-local-system/package.json b/packages/builtin-tool-local-system/package.json
index 027d95114cc..fe36d06e16d 100644
--- a/packages/builtin-tool-local-system/package.json
+++ b/packages/builtin-tool-local-system/package.json
@@ -4,8 +4,7 @@
"private": true,
"exports": {
".": "./src/index.ts",
- "./client": "./src/client/index.ts",
- "./executionRuntime": "./src/ExecutionRuntime/index.ts"
+ "./client": "./src/client/index.ts"
},
"main": "./src/index.ts",
"dependencies": {
diff --git a/packages/builtin-tool-local-system/src/client/executor/index.ts b/packages/builtin-tool-local-system/src/client/executor/index.ts
index a38a5e8ba4f..924735eec8e 100644
--- a/packages/builtin-tool-local-system/src/client/executor/index.ts
+++ b/packages/builtin-tool-local-system/src/client/executor/index.ts
@@ -12,12 +12,12 @@ import type {
RunCommandParams,
WriteLocalFileParams,
} from '@lobechat/electron-client-ipc';
+import { LocalSystemExecutionRuntime } from '@lobechat/tool-runtime';
import type { BuiltinToolResult } from '@lobechat/types';
import { BaseExecutor } from '@lobechat/types';
import { localFileService } from '@/services/electron/localFileService';
-import { LocalSystemExecutionRuntime } from '../../ExecutionRuntime';
import { LocalSystemIdentifier } from '../../types';
import { resolveArgsWithScope } from '../../utils/path';
diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.ts
index 7a1e26be13c..fd561e04fc7 100644
--- a/packages/device-gateway-client/src/http.test.ts
+++ b/packages/device-gateway-client/src/http.test.ts
@@ -137,7 +137,34 @@ describe('GatewayHttpClient', () => {
{ apiName: 'readFile', arguments: '{}', identifier: 'test' },
);
- expect(result).toEqual({ content: 'file contents', error: undefined, success: true });
+ expect(result).toEqual({
+ content: 'file contents',
+ error: undefined,
+ state: undefined,
+ success: true,
+ });
+ });
+
+ it('should preserve structured state alongside content', async () => {
+ // The wire envelope carries `state` separately from `content`. This is
+ // what makes `pluginState` work end-to-end for remote device tool calls.
+ mockFetch({
+ json: vi.fn().mockResolvedValue({
+ content: 'Renamed shell-1 β†’ /tmp/foo',
+ state: { commandId: 'shell-1', exitCode: 0, stdout: 'ok' },
+ success: true,
+ }),
+ ok: true,
+ });
+
+ const result = await client.executeToolCall(
+ { userId: 'user-1' },
+ { apiName: 'runCommand', arguments: '{}', identifier: 'test' },
+ );
+
+ expect(result.content).toBe('Renamed shell-1 β†’ /tmp/foo');
+ expect(result.state).toEqual({ commandId: 'shell-1', exitCode: 0, stdout: 'ok' });
+ expect(result.success).toBe(true);
});
it('should handle non-string content', async () => {
@@ -154,9 +181,13 @@ describe('GatewayHttpClient', () => {
expect(result.content).toBe(JSON.stringify({ key: 'value' }));
});
- it('should handle null/undefined content', async () => {
+ it('should return empty content when content and error are missing', async () => {
+ // Regression guard: previously the client JSON.stringify'd the entire
+ // response body when `content` was missing, leaking `success`/`state`
+ // into the LLM-facing content string. The fix returns empty content
+ // instead β€” the structured payload, if any, is read from `state`.
mockFetch({
- json: vi.fn().mockResolvedValue({ success: true }),
+ json: vi.fn().mockResolvedValue({ success: true, state: { foo: 'bar' } }),
ok: true,
});
@@ -165,8 +196,8 @@ describe('GatewayHttpClient', () => {
{ apiName: 'readFile', arguments: '{}', identifier: 'test' },
);
- // content is undefined, so JSON.stringify(undefined ?? data) -> JSON.stringify(data)
- expect(result.content).toContain('success');
+ expect(result.content).toBe('');
+ expect(result.state).toEqual({ foo: 'bar' });
});
it('should handle missing success field', async () => {
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index e5804ee0e4a..2ba375aba84 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -11,6 +11,7 @@ export interface DeviceStatusResult {
export interface DeviceToolCallResult {
content: string;
error?: string;
+ state?: unknown;
success: boolean;
}
@@ -83,9 +84,22 @@ export class GatewayHttpClient {
const data = await res.json();
return {
+ // Device sends a typed envelope ({ content, state, success }). The legacy
+ // fallback used to JSON.stringify `data.content ?? data` β€” when content
+ // was missing it would stringify the *entire response body* including
+ // `success` and any other top-level fields, which leaked the structured
+ // payload into the LLM-facing content string. Only stringify the
+ // `content` field itself; never fall back to the whole body.
content:
- typeof data.content === 'string' ? data.content : JSON.stringify(data.content ?? data),
+ typeof data.content === 'string'
+ ? data.content
+ : data.content !== undefined && data.content !== null
+ ? JSON.stringify(data.content)
+ : typeof data.error === 'string'
+ ? data.error
+ : '',
error: data.error,
+ state: data.state,
success: data.success ?? true,
};
}
diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.ts
index bca1307602d..1c9445a6b92 100644
--- a/packages/device-gateway-client/src/types.ts
+++ b/packages/device-gateway-client/src/types.ts
@@ -56,6 +56,7 @@ export interface ToolCallResponseMessage {
result: {
content: string;
error?: string;
+ state?: unknown;
success: boolean;
};
type: 'tool_call_response';
diff --git a/packages/prompts/package.json b/packages/prompts/package.json
index 47abad15845..2378365fba5 100644
--- a/packages/prompts/package.json
+++ b/packages/prompts/package.json
@@ -2,6 +2,10 @@
"name": "@lobechat/prompts",
"version": "1.0.0",
"private": true,
+ "exports": {
+ ".": "./src/index.ts",
+ "./fileSystem": "./src/prompts/fileSystem/index.ts"
+ },
"main": "./src/index.ts",
"scripts": {
"test": "vitest",
diff --git a/packages/tool-runtime/src/ComputerRuntime.ts b/packages/tool-runtime/src/ComputerRuntime.ts
index 96eb60331d8..68eac9f2e76 100644
--- a/packages/tool-runtime/src/ComputerRuntime.ts
+++ b/packages/tool-runtime/src/ComputerRuntime.ts
@@ -11,7 +11,7 @@ import {
formatMoveResults,
formatRenameResult,
formatWriteResult,
-} from '@lobechat/prompts';
+} from '@lobechat/prompts/fileSystem';
import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
import type {
diff --git a/packages/builtin-tool-local-system/src/ExecutionRuntime/index.ts b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
similarity index 98%
rename from packages/builtin-tool-local-system/src/ExecutionRuntime/index.ts
rename to packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
index 68e8db1c308..ec208f8d3c0 100644
--- a/packages/builtin-tool-local-system/src/ExecutionRuntime/index.ts
+++ b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
@@ -1,7 +1,8 @@
-import type { ServiceResult } from '@lobechat/tool-runtime';
-import { ComputerRuntime } from '@lobechat/tool-runtime';
import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
+import { ComputerRuntime } from './ComputerRuntime';
+import type { ServiceResult } from './types';
+
/**
* Service interface for local system operations.
* Abstracts the Electron IPC layer so the runtime is testable and decoupled.
@@ -147,7 +148,7 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {
*/
async readFiles(params: any): Promise<BuiltinServerRuntimeOutput> {
try {
- const { formatMultipleFiles } = await import('@lobechat/prompts');
+ const { formatMultipleFiles } = await import('@lobechat/prompts/fileSystem');
const results = await this.service.readLocalFiles(params);
return {
diff --git a/packages/tool-runtime/src/index.ts b/packages/tool-runtime/src/index.ts
index cac3077c129..9389236a2fc 100644
--- a/packages/tool-runtime/src/index.ts
+++ b/packages/tool-runtime/src/index.ts
@@ -1,2 +1,6 @@
export { ComputerRuntime } from './ComputerRuntime';
+export {
+ type ILocalSystemService,
+ LocalSystemExecutionRuntime,
+} from './LocalSystemExecutionRuntime';
export type * from './types';