π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor(local-system): consolidate tool dispatch into a shared runtime entry with cwd injection (#17982)
YuTengjing20afc09c7163
diff --git a/apps/cli/src/tools/localSystemRuntime.ts b/apps/cli/src/tools/localSystemRuntime.tsindex e2a7ceb2fe9..c1e21aa8b8a 100644--- a/apps/cli/src/tools/localSystemRuntime.ts+++ b/apps/cli/src/tools/localSystemRuntime.ts@@ -1,28 +1,12 @@-import path from 'node:path';-import type {BaseFileSearch,- EditFileParams,- GetCommandOutputParams,GlobFilesParams,- GrepContentParams,- KillCommandParams,- ListFilesParams,- ReadFileParams,- RunCommandParams,SearchFilesParams,- WriteFileParams,} from '@lobechat/local-file-shell';import { createFileSearchModule } from '@lobechat/local-file-shell';import { type ILocalSystemService, LocalSystemExecutionRuntime } from '@lobechat/tool-runtime';-import {- editLocalFile,- grepContent,- listLocalFiles,- readLocalFile,- writeLocalFile,-} from './file';+import { editLocalFile, grepContent, listLocalFiles, readLocalFile, writeLocalFile } from './file';import { getCommandOutput, killCommand, runCommand } from './shell';/**@@ -83,39 +67,16 @@ const localSystemService: ILocalSystemService = {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).*+ * The runtime's `executeToolCall` owns legacy alias normalization, IPC field+ * mapping, and cwd/scope forwarding β the server runtime injects the+ * device-bound `cwd`/`scope` into `args` before dispatch, and they now ride+ * through to the local-file-shell functions instead of being dropped.+ ** Returns `null` when `apiName` is not a local-system tool, so the caller can* fall back to CLI-only tools (platform agents).*/@@ -123,96 +84,8 @@ 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 || '',- limit: normalizeLimit(resolved.limit),- } 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,- limit: normalizeLimit(p.limit),- 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;- }- }+ // `trustArgsCwd` β args reach the CLI only after the server runtime has+ // stripped any inbound `cwd` and re-injected the device-bound one, so the+ // `cwd` in `args` here is server-controlled rather than model-chosen.+ return runtime.executeToolCall(apiName, args, { trustArgsCwd: true });}diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex df2c790fa60..b4cb4a78b21 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -5,22 +5,7 @@ import path from 'node:path';import type { DeviceControlDeps } from '@lobechat/device-control';import type { AgentRunRequestMessage, GatewayMcpParams } from '@lobechat/device-gateway-client';-import type {- EditLocalFileParams,- GatewayConnectionStatus,- GetCommandOutputParams,- GlobFilesParams,- GrepContentParams,- KillCommandParams,- ListLocalFileParams,- LocalReadFileParams,- LocalReadFilesParams,- LocalSearchFilesParams,- MoveLocalFilesParams,- RenameLocalFileParams,- RunCommandParams,- WriteLocalFileParams,-} from '@lobechat/electron-client-ipc';+import type { GatewayConnectionStatus } from '@lobechat/electron-client-ipc';import { resolveRemotePlatformCommand } from '@lobechat/heterogeneous-agents/scanHost';import { type ILocalSystemService, LocalSystemExecutionRuntime } from '@lobechat/tool-runtime';import { execa } from 'execa';@@ -112,22 +97,6 @@ interface BuiltinServerRuntimeOutput {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@@ -141,22 +110,6 @@ const safeJsonParse = (input: string): unknown => {}};-/**- * 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*@@ -448,125 +401,20 @@ export default class GatewayConnectionCtr extends ControllerModule {};}- 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,- });- }-- 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,- };- }+ // Local-system tools: one dispatch through the shared runtime entry, which+ // owns legacy alias normalization and IPC field mapping. The server runtime+ // already stripped any model-supplied `cwd` and injected the device-bound+ // `cwd`/`scope` into `args` (see its `WORKING_DIR_ARG` map), so the values+ // here are server-controlled β `trustArgsCwd` lets them ride through to the+ // IPC layer instead of being dropped like the previous per-tool switch did.+ const localSystemOutput = await this.getLocalSystemRuntime().executeToolCall(+ apiName,+ (args ?? {}) as Record<string, unknown>,+ { trustArgsCwd: true },+ );+ if (localSystemOutput) return localSystemOutput;+ switch (apiName) {// βββ Platform agent tools (openclaw / hermes) βββ// These don't go through LocalSystemExecutionRuntime β they return raw// domain payloads that we envelope into BuiltinServerRuntimeOutput here.diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.tsindex 4a3655b6ed7..70f785fa2af 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts@@ -271,11 +271,41 @@ describe('localSystemRuntime', () => {expect(parseArgs()).toEqual({ pattern: '**/*.ts', scope: '/explicit' });});- it('does not override an explicit cwd/scope supplied by the model', async () => {+ // Security: `cwd` is not a manifest field, so a model can never legitimately+ // set it β and the out-of-scope intervention audit does not inspect it. If a+ // provider forwards the unknown argument, honoring it would let+ // `readFile({ path: 'passwd', cwd: '/etc' })` pass the audit (only `path` is+ // checked, and it looks workspace-relative) and then execute against /etc.+ it('overrides an off-contract cwd supplied by the model', async () => {const proxy = buildProxy('/Users/me/repo');await proxy[LocalSystemApiName.runCommand]({ command: 'ls', cwd: '/explicit' });- expect(parseArgs()).toEqual({ command: 'ls', cwd: '/explicit' });+ expect(parseArgs()).toEqual({ command: 'ls', cwd: '/Users/me/repo' });+ });++ it('drops an off-contract cwd on file ops when a working directory is bound', async () => {+ const proxy = buildProxy('/Users/me/repo');+ await proxy[LocalSystemApiName.readFile]({ cwd: '/etc', path: 'passwd' });++ expect(parseArgs()).toEqual({ cwd: '/Users/me/repo', path: 'passwd' });+ });++ // Search apis take `scope`, not `cwd` β but downstream `cwd` doubles as a+ // legacy search-root alias and as the base a relative `scope` resolves+ // against, so leaving it in place would let an audited workspace-relative+ // `scope` execute somewhere else entirely.+ it.each([+ [LocalSystemApiName.globFiles, { cwd: '/', pattern: 'passwd', scope: 'etc' }],+ [LocalSystemApiName.grepContent, { cwd: '/', pattern: 'root', scope: 'etc' }],+ [LocalSystemApiName.searchFiles, { cwd: '/', keywords: 'passwd', scope: 'etc' }],+ ])('strips an off-contract cwd from %s while keeping the audited scope', async (api, args) => {+ mockExecuteToolCall.mockClear();+ const proxy = buildProxy('/Users/me/repo');+ await proxy[api](args);++ const forwarded = JSON.parse(mockExecuteToolCall.mock.calls[0][1].arguments);+ expect(forwarded.cwd).toBeUndefined();+ expect(forwarded.scope).toBe('etc');});it('injects cwd into file ops so the daemon can resolve a relative path', async () => {@@ -315,6 +345,15 @@ describe('localSystemRuntime', () => {expect(parseArgs()).toEqual({ command: 'pwd' });});++ // With nothing trusted to overwrite it with, an off-contract cwd is dropped+ // rather than forwarded β the device then falls back to its own default.+ it('strips an off-contract cwd when no working directory is bound', async () => {+ const proxy = buildProxy(undefined);+ await proxy[LocalSystemApiName.readFile]({ cwd: '/etc', path: 'passwd' });++ expect(parseArgs()).toEqual({ path: 'passwd' });+ });});// A device shell runs the user's own `lh` against their stored credentials,diff --git a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.tsindex 8c373555f4e..dc6c894e193 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts@@ -76,12 +76,34 @@ export const localSystemRuntime: ServerRuntimeRegistration = {// or explicitly passed `.` (a relative reference that resolves to// process.cwd() on the device side β the LobeHub install directory on// packaged desktop instead of the user's actual workspace).- const scopeValue: unknown = workingDirArg ? args?.[workingDirArg] : undefined;- const needsInjection = scopeValue == null || scopeValue === '.';- let finalArgs =- workingDirArg && context.workingDirectory && needsInjection- ? { ...args, [workingDirArg]: context.workingDirectory }- : args;+ //+ // `cwd` and `scope` differ in how much the model is trusted:+ // - `scope` IS a manifest field (the model may legitimately point a+ // search at a subdirectory), and the out-of-scope intervention audit+ // inspects it. Only fill it in when absent/`.`.+ // - `cwd` is NOT in the manifest for ANY api β the model can never+ // legitimately set it, and the audit does not inspect it. So it is+ // stripped from every call before dispatch, and re-added only for the+ // apis that consume it, with the device-bound value.+ //+ // Stripping has to be unconditional, not limited to the `cwd`-arg apis:+ // downstream, `cwd` also acts as a legacy search-root alias and as the+ // base a relative `scope` resolves against. Left in place on a search+ // call, `globFiles({ pattern: 'passwd', scope: 'etc', cwd: '/' })` would+ // be approved by the audit as a workspace-relative `scope` and then+ // execute against `/etc`. Likewise `readFile({ path: 'passwd', cwd:+ // '/etc' })` β only `path` is audited, and it looks workspace-relative.+ const { cwd: _offContractCwd, ...sanitized } = (args ?? {}) as Record<string, unknown>;+ let finalArgs = sanitized as typeof args;+ if (workingDirArg && context.workingDirectory) {+ const scopeValue: unknown = finalArgs?.[workingDirArg];+ // `cwd` was just stripped, so a `cwd`-arg api always needs it back.+ const needsInjection =+ workingDirArg === 'cwd' || scopeValue == null || scopeValue === '.';+ if (needsInjection) {+ finalArgs = { ...finalArgs, [workingDirArg]: context.workingDirectory };+ }+ }// A device shell has its own `lh`, so nothing is rewritten β but the// CLI would resolve to the device credentials' PERSONAL scope, which isdiff --git a/packages/builtin-tool-local-system/src/__tests__/grepContentForwarding.test.ts b/packages/builtin-tool-local-system/src/__tests__/grepContentForwarding.test.tsindex 93af0b589df..c05d93fcb92 100644--- a/packages/builtin-tool-local-system/src/__tests__/grepContentForwarding.test.ts+++ b/packages/builtin-tool-local-system/src/__tests__/grepContentForwarding.test.ts@@ -136,10 +136,13 @@ describe('localSystemExecutor.grepContent β working directory default', () =>it('defaults an omitted scope to ctx.workingDirectory', async () => {const spy = mockRuntime();- await localSystemExecutor.grepContent({ pattern: 'foo' }, {- messageId: 'm1',- workingDirectory: '/Users/me/project',- } as never);+ await localSystemExecutor.grepContent(+ { pattern: 'foo' },+ {+ messageId: 'm1',+ workingDirectory: '/Users/me/project',+ },+ );expect((spy.mock.calls[0][0] as { path?: string }).path).toBe('/Users/me/project');spy.mockRestore();@@ -148,10 +151,13 @@ describe('localSystemExecutor.grepContent β working directory default', () =>it('anchors a relative scope (".") onto ctx.workingDirectory', async () => {const spy = mockRuntime();- await localSystemExecutor.grepContent({ 'pattern': 'foo', 'scope': '.' }, {- messageId: 'm1',- workingDirectory: '/Users/me/project',- } as never);+ await localSystemExecutor.grepContent(+ { pattern: 'foo', scope: '.' },+ {+ messageId: 'm1',+ workingDirectory: '/Users/me/project',+ },+ );expect((spy.mock.calls[0][0] as { path?: string }).path).toBe('/Users/me/project');spy.mockRestore();@@ -160,10 +166,13 @@ describe('localSystemExecutor.grepContent β working directory default', () =>it('keeps an absolute scope as-is even when a working directory is present', async () => {const spy = mockRuntime();- await localSystemExecutor.grepContent({ 'pattern': 'foo', 'scope': '/abs/elsewhere' }, {- messageId: 'm1',- workingDirectory: '/Users/me/project',- } as never);+ await localSystemExecutor.grepContent(+ { pattern: 'foo', scope: '/abs/elsewhere' },+ {+ messageId: 'm1',+ workingDirectory: '/Users/me/project',+ },+ );expect((spy.mock.calls[0][0] as { path?: string }).path).toBe('/abs/elsewhere');spy.mockRestore();@@ -172,7 +181,7 @@ describe('localSystemExecutor.grepContent β working directory default', () =>it('leaves params untouched when no scope and no working directory (web)', async () => {const spy = mockRuntime();- await localSystemExecutor.grepContent({ pattern: 'foo' }, { messageId: 'm1' } as never);+ await localSystemExecutor.grepContent({ pattern: 'foo' }, { messageId: 'm1' });expect((spy.mock.calls[0][0] as { path?: string }).path).toBeUndefined();spy.mockRestore();diff --git a/packages/builtin-tool-local-system/src/client/Intervention/OutOfScopeWarning.tsx b/packages/builtin-tool-local-system/src/client/Intervention/OutOfScopeWarning.tsxindex 81dcdd75b7c..f512fadb8f7 100644--- a/packages/builtin-tool-local-system/src/client/Intervention/OutOfScopeWarning.tsx+++ b/packages/builtin-tool-local-system/src/client/Intervention/OutOfScopeWarning.tsx@@ -1,3 +1,4 @@+import { isPathWithinScope } from '@lobechat/tool-runtime';import { Alert, Flexbox } from '@lobehub/ui';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -8,8 +9,6 @@ import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';import { useElectronStore } from '@/store/electron';-import { isPathWithinScope } from '../../utils/path';-interface OutOfScopeWarningProps {/*** The path(s) to checkdiff --git a/packages/builtin-tool-local-system/src/client/executor/index.test.ts b/packages/builtin-tool-local-system/src/client/executor/index.test.tsindex a59159f96a1..36e03fe3025 100644--- a/packages/builtin-tool-local-system/src/client/executor/index.test.ts+++ b/packages/builtin-tool-local-system/src/client/executor/index.test.ts@@ -187,6 +187,7 @@ describe('LocalSystemExecutor', () => {expect(searchFilesMock).toHaveBeenCalledWith({keywords: 'test',directory: '/home/user/project',+ limit: 100,});});@@ -202,6 +203,7 @@ describe('LocalSystemExecutor', () => {keywords: 'test',scope: '.',directory: '/home/user/project',+ limit: 100,});});@@ -217,6 +219,7 @@ describe('LocalSystemExecutor', () => {keywords: 'test',scope: '/explicit/path',directory: '/explicit/path',+ limit: 100,});});});diff --git a/packages/builtin-tool-local-system/src/client/executor/index.ts b/packages/builtin-tool-local-system/src/client/executor/index.tsindex dfb1b2cfbdb..df2f5abf876 100644--- a/packages/builtin-tool-local-system/src/client/executor/index.ts+++ b/packages/builtin-tool-local-system/src/client/executor/index.ts@@ -19,9 +19,6 @@ import { BaseExecutor } from '@lobechat/types';import { localFileService } from '@/services/electron/localFileService';import { LocalSystemIdentifier } from '../../types';-import { resolveArgsWithScope, resolvePathWithScope } from '../../utils/path';--const DEFAULT_FILE_SEARCH_LIMIT = 100;const LocalSystemApiEnum = {editFile: 'editFile' as const,@@ -41,8 +38,14 @@ const LocalSystemApiEnum = {/*** Local System Tool Executor*- * Delegates standard computer operations to LocalSystemExecutionRuntime (extends ComputerRuntime).- * Handles scope resolution for paths before delegating.+ * Thin adapter over `LocalSystemExecutionRuntime.executeToolCall`, which owns+ * legacy alias normalization, IPC field mapping, and working-directory+ * anchoring for every tool. The executor only contributes the two things the+ * runtime can't know:+ * - `ctx.workingDirectory` β the agent's effective working directory, sourced+ * from the same place as the `{{workingDirectory}}` prompt placeholder, so+ * what tools operate on matches what the prompt promises;+ * - the `BuiltinServerRuntimeOutput` β `BuiltinToolResult` conversion.*/class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {readonly identifier = LocalSystemIdentifier;@@ -50,6 +53,28 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {private runtime = new LocalSystemExecutionRuntime(localFileService);+ private execute = async (+ apiName: keyof typeof LocalSystemApiEnum,+ params: Record<string, any>,+ ctx?: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ try {+ // `trustArgsCwd` stays off: `params` came straight from the model, and+ // `ctx.workingDirectory` is undefined whenever the agent has none+ // configured β so an off-contract `cwd` must be dropped here rather than+ // mistaken for a server-injected one.+ const output = await this.runtime.executeToolCall(apiName, params, {+ workingDirectory: ctx?.workingDirectory,+ });+ // apiEnum and the runtime dispatch cover the same tool set, so a null+ // (unknown tool) here is a programming error, not a user-facing state.+ if (!output) return this.errorResult(new Error(`Unknown local-system API: ${apiName}`));+ return this.toResult(output);+ } catch (error) {+ return this.errorResult(error);+ }+ };+/*** Convert BuiltinServerRuntimeOutput to BuiltinToolResult.*@@ -86,191 +111,45 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {// ==================== File Operations ====================- listFiles = async (params: ListLocalFileParams): Promise<BuiltinToolResult> => {- try {- const result = await this.runtime.listFiles({- directoryPath: params.path,- limit: params.limit,- sortBy: params.sortBy,- sortOrder: params.sortOrder,- } as any);- return this.toResult(result);- } catch (error) {- return this.errorResult(error);- }- };+ listFiles = (params: ListLocalFileParams, ctx?: BuiltinToolContext) =>+ this.execute('listFiles', params, ctx);- readFile = async (params: LocalReadFileParams): Promise<BuiltinToolResult> => {- try {- const result = await this.runtime.readFile({- endLine: params.loc?.[1],- path: params.path,- startLine: params.loc?.[0],- });- return this.toResult(result);- } catch (error) {- return this.errorResult(error);- }- };+ readFile = (params: LocalReadFileParams, ctx?: BuiltinToolContext) =>+ this.execute('readFile', params, ctx);- readFiles = async (params: LocalReadFilesParams): Promise<BuiltinToolResult> => {- try {- const result = await this.runtime.readFiles(params);- return this.toResult(result);- } catch (error) {- return this.errorResult(error);- }- };+ readFiles = (params: LocalReadFilesParams, ctx?: BuiltinToolContext) =>+ this.execute('readFiles', params, ctx);- searchFiles = async (- params: LocalSearchFilesParams,- ctx?: BuiltinToolContext,- ): Promise<BuiltinToolResult> => {- try {- const resolvedParams = resolveArgsWithScope(params, 'directory', ctx?.workingDirectory);- const result = await this.runtime.searchFiles({- ...resolvedParams,- directory: resolvedParams.directory || '',- });- return this.toResult(result);- } catch (error) {- return this.errorResult(error);- }- };+ searchFiles = (params: LocalSearchFilesParams, ctx?: BuiltinToolContext) =>+ this.execute('searchFiles', params, ctx);- moveFiles = async (params: MoveLocalFilesParams): Promise<BuiltinToolResult> => {- try {- const result = await this.runtime.moveFiles({- operations: params.items.map((item) => ({- destination: item.newPath,- source: item.oldPath,- })),- });- return this.toResult(result);- } catch (error) {- return this.errorResult(error);- }- };+ moveFiles = (params: MoveLocalFilesParams, ctx?: BuiltinToolContext) =>+ this.execute('moveFiles', params, ctx);- writeFile = async (params: WriteLocalFileParams): Promise<BuiltinToolResult> => {- try {- const result = await this.runtime.writeFile(params);- return this.toResult(result);- } catch (error) {- return this.errorResult(error);- }- };+ writeFile = (params: WriteLocalFileParams, ctx?: BuiltinToolContext) =>+ this.execute('writeFile', params, ctx);- editFile = async (params: EditLocalFileParams): Promise<BuiltinToolResult> => {- try {- const result = await this.runtime.editFile({- all: params.replace_all,- path: params.file_path,- replace: params.new_string,- search: params.old_string,- });- return this.toResult(result);- } catch (error) {- return this.errorResult(error);- }- };+ editFile = (params: EditLocalFileParams, ctx?: BuiltinToolContext) =>+ this.execute('editFile', params, ctx);// ==================== Shell Commands ====================- runCommand = async (params: RunCommandParams): Promise<BuiltinToolResult> => {- try {- // The manifest exposes `run_in_background`, but ComputerRuntime's RunCommandState- // reads `args.background` for the `isBackground` field β without this normalize- // the UI/state would always say foreground even for background commands.- // The IPC handler reads `run_in_background` itself, so we keep that field too.- const result = await this.runtime.runCommand({- ...params,- background: params.run_in_background,- } as any);- return this.toResult(result);- } catch (error) {- return this.errorResult(error);- }- };+ runCommand = (params: RunCommandParams, ctx?: BuiltinToolContext) =>+ this.execute('runCommand', params, ctx);- getCommandOutput = async (params: GetCommandOutputParams): Promise<BuiltinToolResult> => {- try {- const result = await this.runtime.getCommandOutput({- commandId: params.shell_id,- filter: params.filter,- } as any);- return this.toResult(result);- } catch (error) {- return this.errorResult(error);- }- };+ getCommandOutput = (params: GetCommandOutputParams, ctx?: BuiltinToolContext) =>+ this.execute('getCommandOutput', params, ctx);- killCommand = async (params: KillCommandParams): Promise<BuiltinToolResult> => {- try {- const result = await this.runtime.killCommand({- commandId: params.shell_id,- });- return this.toResult(result);- } catch (error) {- return this.errorResult(error);- }- };+ killCommand = (params: KillCommandParams, ctx?: BuiltinToolContext) =>+ this.execute('killCommand', params, ctx);// ==================== Search & Find ====================- grepContent = async (- params: GrepContentParams,- ctx?: BuiltinToolContext,- ): Promise<BuiltinToolResult> => {- try {- // Resolve the search root to an ABSOLUTE path anchored on the agent's- // effective working directory. The grep manifest/systemRole tell the model- // `scope` "defaults to the working directory", but without this the- // downstream `resolveSearchPath` drops to the Electron main process- // `process.cwd()` (`/` in a packaged app) β so a scope-less OR relative- // (e.g. `.`) scope made every grep return 0 matches. `ctx.workingDirectory`- // is sourced from the same place as the `{{workingDirectory}}` prompt- // placeholder, so what the search targets matches what the prompt promises.- // `resolvePathWithScope(scope, workingDir)` treats the model's `scope` as a- // path resolved against the working directory:- // - scope omitted β working directory- // - scope relative (`.`, `src`) β joined onto the working directory- // - scope absolute β used as-is- // It only returns undefined when there is no working directory AND no scope- // (web / nothing configured) β then we leave params untouched.- const searchRoot = resolvePathWithScope(params.scope, ctx?.workingDirectory);- const resolvedParams = searchRoot ? { ...params, path: searchRoot } : params;- // Forward the full IPC params (glob / output_mode / -i / -A / -B / -C / -n /- // multiline / head_limit / type / tool) instead of stripping to {directory, pattern}.- // ComputerRuntime.callService passes args through unchanged, so the runtime type- // narrowing was the only blocker β the underlying rg/grep needs these flags to- // honor the agent's filter and stop scanning dist/* and tsbuildinfo.- const result = await this.runtime.grepContent(resolvedParams as any);- return this.toResult(result);- } catch (error) {- return this.errorResult(error);- }- };+ grepContent = (params: GrepContentParams, ctx?: BuiltinToolContext) =>+ this.execute('grepContent', params, ctx);- globFiles = async (- params: GlobFilesParams,- ctx?: BuiltinToolContext,- ): Promise<BuiltinToolResult> => {- try {- const resolvedScope = resolvePathWithScope(params.scope, ctx?.workingDirectory);- const result = await this.runtime.globFiles({- directory: resolvedScope,- limit:- Number.isFinite(params.limit) && params.limit && params.limit > 0- ? Math.floor(params.limit)- : DEFAULT_FILE_SEARCH_LIMIT,- pattern: params.pattern,- });- return this.toResult(result);- } catch (error) {- return this.errorResult(error);- }- };+ globFiles = (params: GlobFilesParams, ctx?: BuiltinToolContext) =>+ this.execute('globFiles', params, ctx);// ==================== Helpers ====================diff --git a/packages/builtin-tool-local-system/src/interventionAudit.ts b/packages/builtin-tool-local-system/src/interventionAudit.tsindex d1467976f10..c44e472c3d5 100644--- a/packages/builtin-tool-local-system/src/interventionAudit.ts+++ b/packages/builtin-tool-local-system/src/interventionAudit.ts@@ -1,7 +1,6 @@+import { normalizePathForScope, resolvePathWithScope } from '@lobechat/tool-runtime';import { type DynamicInterventionResolver } from '@lobechat/types';-import { normalizePathForScope, resolvePathWithScope } from './utils/path';-const SAFE_PATH_PREFIXES = ['/tmp', '/var/tmp'] as const;interface SafePathAuditParams {diff --git a/packages/tool-runtime/package.json b/packages/tool-runtime/package.jsonindex 49ac7008576..3ad154b486a 100644--- a/packages/tool-runtime/package.json+++ b/packages/tool-runtime/package.json@@ -7,7 +7,8 @@},"main": "./src/index.ts","dependencies": {- "@lobechat/prompts": "workspace:*"+ "@lobechat/prompts": "workspace:*",+ "path-browserify-esm": "*"},"devDependencies": {"@lobechat/types": "workspace:*"diff --git a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts b/packages/tool-runtime/src/LocalSystemExecutionRuntime.tsindex ba134d19c4e..93095a5cb55 100644--- a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts+++ b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts@@ -1,6 +1,7 @@import type { BuiltinServerRuntimeOutput } from '@lobechat/types';import { ComputerRuntime } from './ComputerRuntime';+import { resolveArgsWithScope, resolvePathWithScope } from './pathScope';import type { ServiceResult } from './types';/**@@ -42,6 +43,56 @@ const SERVICE_METHOD_MAP: Record<string, keyof ILocalSystemService> = {writeLocalFile: 'writeFile',};+/**+ * 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',+ moveLocalFiles: 'moveFiles',+ readLocalFile: 'readFile',+ renameLocalFile: 'renameFile',+ searchLocalFiles: 'searchFiles',+ writeLocalFile: 'writeFile',+};++/**+ * Default cap for glob/search results when the caller didn't ask for a limit.+ * Matches the manifest's documented default.+ */+const DEFAULT_FILE_SEARCH_LIMIT = 100;++const normalizeLimit = (limit?: number) =>+ Number.isFinite(limit) && limit && limit > 0 ? Math.floor(limit) : DEFAULT_FILE_SEARCH_LIMIT;++export interface ExecuteLocalToolOptions {+ /**+ * Whether `args.cwd` may be trusted as a search/spawn root.+ *+ * `cwd` is not a manifest field for any api, so a model can never legitimately+ * set one β but the gateway and CLI paths receive args that the server runtime+ * already sanitized (it strips every inbound `cwd` and re-injects the+ * device-bound value; see `serverRuntimes/localSystem.ts`), and that injected+ * value has to survive.+ *+ * Callers must state which side of that boundary they are on rather than+ * letting the runtime infer it: a renderer call for an agent with no+ * configured working directory is indistinguishable from a gateway call if the+ * runtime only looks at whether `workingDirectory` is set.+ *+ * @default false+ */+ trustArgsCwd?: boolean;+ /**+ * The agent's effective working directory (absolute). Sourced from the same+ * place as the `{{workingDirectory}}` prompt placeholder, so what tools+ * operate on matches what the prompt promises.+ */+ workingDirectory?: string;+}+/*** Local System Execution Runtime*@@ -57,6 +108,166 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {this.service = service;}+ /**+ * Single entry point for dispatching a raw tool call (manifest / IPC shaped+ * args, snake_case field names) to the typed ComputerRuntime methods.+ *+ * This is THE place where three concerns converge β every caller (renderer+ * executor, desktop gateway, CLI) used to keep its own partial copy of them,+ * which is how the "half-fixed cwd injection" family of bugs happened:+ *+ * 1. **Legacy alias normalization** β older gateways send `readLocalFile`+ * etc.; normalized to the current tool names.+ * 2. **Working-directory anchoring** β mirrors the server runtime's+ * `WORKING_DIR_ARG` injection. Shell + file ops get `cwd`, search ops get+ * their search root resolved via {@link resolvePathWithScope}. Without it+ * the service layer falls back to its own `process.cwd()` β the app+ * install directory in a packaged desktop app (or `/`), NOT the user's+ * workspace. Server-injected values already present in `args` win: they+ * are resolved against the working directory rather than replaced.+ * 3. **Field mapping** β IPC names (`file_path`, `shell_id`,+ * `run_in_background`, `loc`) β the normalized names ComputerRuntime+ * reads when building state/content. `denormalizeParams` maps them back+ * to IPC names right before the service call.+ *+ * Returns `null` when `apiName` is not a local-system tool so callers can+ * fall back to their own tools (platform agents, browser, β¦).+ */+ async executeToolCall(+ apiName: string,+ args: Record<string, any>,+ options?: ExecuteLocalToolOptions,+ ): Promise<BuiltinServerRuntimeOutput | null> {+ const name = LEGACY_API_ALIASES[apiName] ?? apiName;+ const workingDirectory = options?.workingDirectory;+ // Trust boundary β `cwd` is never a manifest field, so no legitimate call+ // carries a model-chosen one, and the out-of-scope intervention audit does+ // not inspect it (it reads `path`/`file_path`/`directory`/`scope`). Left+ // trusted, `readFile({ path: 'passwd', cwd: '/etc' })` would look+ // workspace-relative to the audit and then execute against `/etc`.+ //+ // Which side of the boundary a call is on comes from the caller's explicit+ // `trustArgsCwd`, never from whether `workingDirectory` happens to be set:+ // a renderer call for an agent with no configured working directory leaves+ // both undefined, and inferring "no workingDirectory β server-sanitized"+ // would hand that call the model's own `cwd`.+ const trustedArgsCwd = options?.trustArgsCwd ? args.cwd : undefined;+ const cwd = workingDirectory ?? trustedArgsCwd;++ switch (name) {+ case 'listFiles': {+ return this.listFiles({+ cwd,+ directoryPath: args.path,+ limit: args.limit,+ sortBy: args.sortBy,+ sortOrder: args.sortOrder,+ });+ }++ case 'readFile': {+ return this.readFile({+ cwd,+ endLine: args.loc?.[1],+ path: args.path,+ startLine: args.loc?.[0],+ });+ }++ case 'readFiles': {+ return this.readFiles({ ...args, cwd });+ }++ case 'writeFile': {+ return this.writeFile({ content: args.content, cwd, path: args.path });+ }++ case 'editFile': {+ return this.editFile({+ all: args.replace_all,+ cwd,+ path: args.file_path,+ replace: args.new_string,+ search: args.old_string,+ });+ }++ case 'moveFiles': {+ return this.moveFiles({+ cwd,+ operations:+ args.items?.map((item: { newPath: string; oldPath: string }) => ({+ destination: item.newPath,+ source: item.oldPath,+ })) ?? [],+ });+ }++ case 'renameFile': {+ return this.renameFile({ newName: args.newName, oldPath: args.path });+ }++ case 'runCommand': {+ // ComputerRuntime's RunCommandState reads `background` for `isBackground`;+ // the manifest exposes `run_in_background`. Keep the original field too β+ // the IPC handler reads `run_in_background` itself.+ return this.runCommand({+ ...args,+ background: args.run_in_background,+ command: args.command,+ cwd,+ });+ }++ case 'getCommandOutput': {+ return this.getCommandOutput({+ commandId: args.shell_id,+ filter: args.filter,+ timeout: args.timeout,+ });+ }++ case 'killCommand': {+ return this.killCommand({ commandId: args.shell_id });+ }++ case 'grepContent': {+ // Anchor the search root on the working directory and forward the FULL+ // param set (glob / output_mode / -i / -A / β¦ ) β stripping flags here+ // silently defeated the agent's filters in the past. `cwd` is a legacy+ // search-root alias that takes precedence downstream β strip a+ // model-supplied one on the audited path (see trust boundary above).+ return this.grepContent({+ ...resolveArgsWithScope(args, 'path', workingDirectory),+ // `cwd` outranks the resolved `path` downstream, so the resolved root+ // must not be shadowed by an untrusted value; keep it only when the+ // caller vouched for it (gateway / CLI, post-sanitization).+ cwd: workingDirectory ? undefined : trustedArgsCwd,+ pattern: args.pattern,+ });+ }++ case 'globFiles': {+ // `cwd` is a legacy alias for `scope` β only honored when trusted (see+ // trust boundary above).+ return this.globFiles({+ directory: resolvePathWithScope(args.scope, cwd),+ limit: normalizeLimit(args.limit),+ pattern: args.pattern,+ });+ }++ case 'searchFiles': {+ const resolved = resolveArgsWithScope(args, 'directory', workingDirectory);+ return this.searchFiles({ ...resolved, limit: normalizeLimit(resolved.limit) });+ }++ default: {+ return null;+ }+ }+ }+protected async callService(toolName: string,params: Record<string, any>,@@ -82,6 +293,7 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {switch (toolName) {case 'editLocalFile': {return {+ cwd: params.cwd,file_path: params.path,new_string: params.replace,old_string: params.search,@@ -91,6 +303,7 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {case 'listLocalFiles': {return {+ cwd: params.cwd,limit: params.limit,path: params.directoryPath,sortBy: params.sortBy,@@ -100,6 +313,7 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {case 'moveLocalFiles': {return {+ cwd: params.cwd,items: params.operations?.map((op: any) => ({newPath: op.destination,oldPath: op.source,@@ -127,7 +341,14 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {params.startLine !== undefined || params.endLine !== undefined? [params.startLine ?? 0, params.endLine ?? 200]: undefined;- return { fullContent: params.fullContent, loc, path: params.path };+ return { cwd: params.cwd, fullContent: params.fullContent, loc, path: params.path };+ }++ case 'runCommand': {+ // Map the normalized `background` back to the IPC `run_in_background`+ // (kept when already present). `cwd` rides through via the spread β+ // without it the shell spawns in the service's own process cwd.+ return { ...params, run_in_background: params.run_in_background ?? params.background };}case 'globLocalFiles': {diff --git a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.tsindex b48d0638f37..b2d7048b1b2 100644--- a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts+++ b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts@@ -155,7 +155,7 @@ describe('LocalSystemExecutionRuntime.grepContent', () => {'path': '/repo','pattern': 'Foo','type': 'ts',- } as never);+ });const forwarded = (service.grepContent as ReturnType<typeof vi.fn>).mock.calls[0][0];@@ -242,3 +242,305 @@ describe('LocalSystemExecutionRuntime.readFile', () => {expect(output.content).toContain('hello');});});++describe('LocalSystemExecutionRuntime.executeToolCall β working directory anchoring', () => {+ const WD = '/Users/me/project';++ // Regression: the desktop executor spawned shells in the app install+ // directory because no cwd ever reached the IPC layer. The runner spawns in+ // `params.cwd`, so it MUST carry the agent's working directory.+ it('injects the working directory as runCommand cwd and maps run_in_background', async () => {+ const service = createService({+ runCommand: vi.fn().mockResolvedValue({ exit_code: 0, stdout: 'ok', success: true }),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ await runtime.executeToolCall(+ 'runCommand',+ { command: 'ls', run_in_background: true },+ { workingDirectory: WD },+ );++ expect(service.runCommand).toHaveBeenCalledWith(+ expect.objectContaining({ command: 'ls', cwd: WD, run_in_background: true }),+ );+ });++ it('keeps a server-injected absolute cwd (gateway path, trustArgsCwd)', async () => {+ const service = createService({+ runCommand: vi.fn().mockResolvedValue({ exit_code: 0, success: true }),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ await runtime.executeToolCall(+ 'runCommand',+ { command: 'ls', cwd: '/from/server' },+ { trustArgsCwd: true },+ );++ expect(service.runCommand).toHaveBeenCalledWith(+ expect.objectContaining({ command: 'ls', cwd: '/from/server' }),+ );+ });++ // Security: an agent with no configured working directory leaves BOTH+ // `workingDirectory` and `trustArgsCwd` unset on the renderer path, which is+ // exactly the shape a gateway call has. Inferring trust from the missing+ // working directory would hand this call the model's own `cwd`, so the+ // contract has to be explicit.+ it.each([+ ['runCommand', { command: 'cat passwd', cwd: '/etc' }, 'runCommand'],+ ['readFile', { cwd: '/etc', path: 'passwd' }, 'readLocalFile'],+ ] as const)(+ 'drops a model-supplied cwd for %s when the caller did not vouch for it',+ async (api, args, serviceMethod) => {+ const service = createService({+ [serviceMethod]: vi.fn().mockResolvedValue({ success: true }),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ await runtime.executeToolCall(api, { ...args });++ expect(service[serviceMethod]).toHaveBeenCalledWith(+ expect.objectContaining({ cwd: undefined }),+ );+ },+ );++ it('drops a model-supplied cwd from grepContent when the caller did not vouch for it', async () => {+ const grepContent = vi.fn().mockResolvedValue({ matches: [], success: true, total_matches: 0 });+ const runtime = new LocalSystemExecutionRuntime(createService({ grepContent }));++ await runtime.executeToolCall('grepContent', { cwd: '/etc', pattern: 'root', scope: '.' });++ // `cwd` outranks `path` as the search root downstream, so the model's value+ // must not survive β the audited relative scope is what remains.+ const forwarded = grepContent.mock.calls[0][0];+ expect(forwarded.cwd).not.toBe('/etc');+ expect(forwarded.path).not.toBe('/etc');+ });++ // Security: the out-of-scope intervention audit inspects path/scope fields+ // but not `cwd`. A model-supplied cwd on the audited (renderer) path could+ // smuggle a relative path outside the workspace β it must be ignored.+ it('ignores a model-supplied cwd when a trusted working directory is present', async () => {+ const service = createService({+ runCommand: vi.fn().mockResolvedValue({ exit_code: 0, success: true }),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ await runtime.executeToolCall(+ 'runCommand',+ { command: 'cat passwd', cwd: '/etc' },+ { workingDirectory: WD },+ );++ expect(service.runCommand).toHaveBeenCalledWith(expect.objectContaining({ cwd: WD }));+ });++ it('ignores a model-supplied cwd for file ops on the audited path', async () => {+ const service = createService({+ readLocalFile: vi.fn().mockResolvedValue({ content: '', success: true }),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ await runtime.executeToolCall(+ 'readFile',+ { cwd: '/etc', path: 'passwd' },+ { workingDirectory: WD },+ );++ expect(service.readLocalFile).toHaveBeenCalledWith(expect.objectContaining({ cwd: WD }));+ });++ it('ignores a model-supplied grep/glob cwd alias on the audited path', async () => {+ const service = createService({+ globFiles: vi.fn().mockResolvedValue({ files: [], success: true, total_files: 0 }),+ grepContent: vi.fn().mockResolvedValue({ matches: [], success: true, total_matches: 0 }),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ await runtime.executeToolCall(+ 'globFiles',+ { cwd: '/etc', pattern: '*' },+ { workingDirectory: WD },+ );+ expect(service.globFiles).toHaveBeenCalledWith(expect.objectContaining({ scope: WD }));++ await runtime.executeToolCall(+ 'grepContent',+ { cwd: '/etc', pattern: 'root' },+ { workingDirectory: WD },+ );+ const grepForwarded = (service.grepContent as ReturnType<typeof vi.fn>).mock.calls[0][0];+ expect(grepForwarded.cwd).toBe(WD);+ expect(grepForwarded.path).toBe(WD);+ });++ it.each([+ [+ 'readFile',+ { path: 'src/a.ts' },+ 'readLocalFile',+ { cwd: WD, fullContent: undefined, loc: undefined, path: 'src/a.ts' },+ ],+ [+ 'writeFile',+ { content: 'x', path: 'src/a.ts' },+ 'writeFile',+ { content: 'x', cwd: WD, path: 'src/a.ts' },+ ],+ [+ 'editFile',+ { file_path: 'a.ts', new_string: 'b', old_string: 'a' },+ 'editLocalFile',+ {+ cwd: WD,+ file_path: 'a.ts',+ new_string: 'b',+ old_string: 'a',+ replace_all: undefined,+ },+ ],+ [+ 'moveFiles',+ { items: [{ newPath: 'b.ts', oldPath: 'a.ts' }] },+ 'moveLocalFiles',+ { cwd: WD, items: [{ newPath: 'b.ts', oldPath: 'a.ts' }] },+ ],+ [+ 'listFiles',+ { path: '.' },+ 'listLocalFiles',+ { cwd: WD, limit: undefined, path: '.', sortBy: undefined, sortOrder: undefined },+ ],+ ] as const)(+ 'forwards the working directory as cwd for %s',+ async (apiName, args, serviceMethod, expected) => {+ const service = createService({+ [serviceMethod]: vi.fn().mockResolvedValue({ replacements: 1, success: true }),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ await runtime.executeToolCall(apiName, args as Record<string, any>, {+ workingDirectory: WD,+ });++ expect(service[serviceMethod as keyof ILocalSystemService]).toHaveBeenCalledWith(expected);+ },+ );++ it('forwards cwd to readFiles (direct service call path)', async () => {+ const service = createService({+ readLocalFiles: vi.fn().mockResolvedValue([]),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ await runtime.executeToolCall(+ 'readFiles',+ { paths: ['a.ts', 'b.ts'] },+ { workingDirectory: WD },+ );++ expect(service.readLocalFiles).toHaveBeenCalledWith({ cwd: WD, paths: ['a.ts', 'b.ts'] });+ });++ it('anchors an omitted grep scope onto the working directory with full param forwarding', async () => {+ const service = createService({+ grepContent: vi.fn().mockResolvedValue({ matches: [], success: true, total_matches: 0 }),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ await runtime.executeToolCall(+ 'grepContent',+ { '-i': true, 'glob': '**/*.ts', 'pattern': 'foo' },+ { workingDirectory: WD },+ );++ const forwarded = (service.grepContent as ReturnType<typeof vi.fn>).mock.calls[0][0];+ expect(forwarded).toMatchObject({ '-i': true, 'glob': '**/*.ts', 'pattern': 'foo' });+ expect(forwarded.path ?? forwarded.scope ?? forwarded.cwd).toBe(WD);+ });++ it('resolves glob scope "." to the working directory', async () => {+ const service = createService({+ globFiles: vi.fn().mockResolvedValue({ files: [], success: true, total_files: 0 }),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ await runtime.executeToolCall(+ 'globFiles',+ { pattern: '**/*.ts', scope: '.' },+ { workingDirectory: WD },+ );++ expect(service.globFiles).toHaveBeenCalledWith({ limit: 100, pattern: '**/*.ts', scope: WD });+ });++ it('defaults the searchFiles directory to the working directory', async () => {+ const service = createService({+ searchLocalFiles: vi.fn().mockResolvedValue([]),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ await runtime.executeToolCall('searchFiles', { keywords: 'foo' }, { workingDirectory: WD });++ expect(service.searchLocalFiles).toHaveBeenCalledWith(+ expect.objectContaining({ directory: WD, keywords: 'foo', limit: 100 }),+ );+ });+});++describe('LocalSystemExecutionRuntime.executeToolCall β dispatch', () => {+ it('normalizes legacy API aliases (readLocalFile β readFile)', async () => {+ const service = createService({+ readLocalFile: vi.fn().mockResolvedValue({ content: 'hi', success: true }),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ const output = await runtime.executeToolCall('readLocalFile', { path: '/tmp/a.txt' });++ expect(output?.success).toBe(true);+ expect(service.readLocalFile).toHaveBeenCalled();+ });++ it('routes legacy renameLocalFile through the typed renameFile method', async () => {+ const service = createService({+ renameLocalFile: vi.fn().mockResolvedValue({ newPath: '/tmp/b.txt', success: true }),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ const output = await runtime.executeToolCall('renameLocalFile', {+ newName: 'b.txt',+ path: '/tmp/a.txt',+ });++ expect(output?.success).toBe(true);+ expect(service.renameLocalFile).toHaveBeenCalledWith({ newName: 'b.txt', path: '/tmp/a.txt' });+ });++ it('maps shell_id to commandId and forwards filter/timeout for getCommandOutput', async () => {+ const service = createService({+ getCommandOutput: vi.fn().mockResolvedValue({ exit_code: 0, stdout: '', success: true }),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ await runtime.executeToolCall('getCommandOutput', {+ filter: 'ERROR',+ shell_id: 'sh-1',+ timeout: 5000,+ });++ expect(service.getCommandOutput).toHaveBeenCalledWith({+ filter: 'ERROR',+ shell_id: 'sh-1',+ timeout: 5000,+ });+ });++ it('returns null for non-local-system tools so callers can fall back', async () => {+ const runtime = new LocalSystemExecutionRuntime(createService());++ expect(await runtime.executeToolCall('runHeteroTask', {})).toBeNull();+ });+});diff --git a/packages/builtin-tool-local-system/src/utils/__tests__/path.test.ts b/packages/tool-runtime/src/__tests__/pathScope.test.tssimilarity index 99%rename from packages/builtin-tool-local-system/src/utils/__tests__/path.test.tsrename to packages/tool-runtime/src/__tests__/pathScope.test.tsindex 58c3a4534f6..4e3fb2be5f4 100644--- a/packages/builtin-tool-local-system/src/utils/__tests__/path.test.ts+++ b/packages/tool-runtime/src/__tests__/pathScope.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { normalizePathForScope, resolveArgsWithScope, resolvePathWithScope } from '../path';+import { normalizePathForScope, resolveArgsWithScope, resolvePathWithScope } from '../pathScope';describe('normalizePathForScope', () => {it('should normalize a simple absolute path', () => {diff --git a/packages/tool-runtime/src/index.ts b/packages/tool-runtime/src/index.tsindex 9389236a2fc..71e8e3098bf 100644--- a/packages/tool-runtime/src/index.ts+++ b/packages/tool-runtime/src/index.ts@@ -1,6 +1,13 @@export { ComputerRuntime } from './ComputerRuntime';export {+ type ExecuteLocalToolOptions,type ILocalSystemService,LocalSystemExecutionRuntime,} from './LocalSystemExecutionRuntime';+export {+ isPathWithinScope,+ normalizePathForScope,+ resolveArgsWithScope,+ resolvePathWithScope,+} from './pathScope';export type * from './types';diff --git a/packages/builtin-tool-local-system/src/utils/path.ts b/packages/tool-runtime/src/pathScope.tssimilarity index 100%rename from packages/builtin-tool-local-system/src/utils/path.tsrename to packages/tool-runtime/src/pathScope.tsdiff --git a/packages/tool-runtime/src/types.ts b/packages/tool-runtime/src/types.tsindex f6d26115c47..b804fcf21ad 100644--- a/packages/tool-runtime/src/types.ts+++ b/packages/tool-runtime/src/types.ts@@ -11,12 +11,17 @@ export interface ServiceResult {// ==================== Params ====================export interface ListFilesParams {+ /** Working directory a relative `directoryPath` resolves against on the service side. */+ cwd?: string;directoryPath: string;+ limit?: number;sortBy?: string;sortOrder?: string;}export interface ReadFileParams {+ /** Working directory a relative `path` resolves against on the service side. */+ cwd?: string;endLine?: number;path: string;startLine?: number;@@ -25,11 +30,15 @@ export interface ReadFileParams {export interface WriteFileParams {content: string;createDirectories?: boolean;+ /** Working directory a relative `path` resolves against on the service side. */+ cwd?: string;path: string;}export interface EditFileParams {all?: boolean;+ /** Working directory a relative `path` resolves against on the service side. */+ cwd?: string;path: string;replace: string;search: string;@@ -40,7 +49,7 @@ export interface SearchFilesParams {createdAfter?: string;createdBefore?: string;detailed?: boolean;- directory: string;+ directory?: string;exclude?: string[];/** @deprecated Prefer `fileTypes` (plural). Retained for cloud sandbox back-compat. */fileType?: string;@@ -58,6 +67,8 @@ export interface SearchFilesParams {}export interface MoveFilesParams {+ /** Working directory each operation's relative paths resolve against on the service side. */+ cwd?: string;operations: Array<{destination: string;source: string;@@ -78,11 +89,20 @@ export interface GlobFilesParams {export interface RunCommandParams {background?: boolean;command: string;+ /**+ * Working directory the shell spawns in. Without it the service falls back to+ * its own process cwd (the app install directory in a packaged desktop app).+ */+ cwd?: string;+ description?: string;+ env?: Record<string, string>;timeout?: number;}export interface GetCommandOutputParams {commandId: string;+ /** Regex filter applied to the returned output lines. */+ filter?: 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@@ -95,11 +115,38 @@ export interface KillCommandParams {commandId: string;}+/**+ * Grep params mirror the tool manifest / IPC contract (`local-file-shell`'s+ * `GrepContentParams`): the full flag set must survive to the service layer so+ * the underlying rg/grep honors the agent's filters. `ComputerRuntime` itself+ * only reads `pattern`; everything else is forwarded verbatim.+ */export interface GrepContentParams {- directory: string;- filePattern?: string;- pattern: string;- recursive?: boolean;+ '-A'?: number;+ '-B'?: number;+ '-C'?: number;+ '-i'?: boolean;+ '-n'?: boolean;+ /** Legacy alias for the search root. Prefer `path`/`scope`. */+ 'cwd'?: string;+ /** @deprecated Legacy alias for the search root. Prefer `path`/`scope`. */+ 'directory'?: string;+ /** @deprecated Legacy alias for `glob`. */+ 'filePattern'?: string;+ /** ripgrep-style glob filter on file paths. */+ 'glob'?: string;+ 'head_limit'?: number;+ 'multiline'?: boolean;+ 'output_mode'?: 'content' | 'count' | 'files_with_matches';+ /** Absolute search root. Takes precedence over `scope` on the service side. */+ 'path'?: string;+ 'pattern': string;+ 'recursive'?: boolean;+ /** Working directory scope limiting the search. */+ 'scope'?: string;+ /** Preferred search tool. */+ 'tool'?: 'ag' | 'grep' | 'rg';+ 'type'?: string;}// ==================== State ====================