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(device): inject device-bound working directory into server local-system tool chain (#15887)

Arvin Xu5dea7683975d
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.ts
index 23367220fb9..2bf2af3ddc1 100644
--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts
+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts
@@ -366,14 +366,14 @@ export default class LocalFileCtr extends ControllerModule {
}
@IpcMethod()
- async readFiles({ paths }: LocalReadFilesParams): Promise<LocalReadFileResult[]> {
+ async readFiles({ paths, cwd }: LocalReadFilesParams): Promise<LocalReadFileResult[]> {
logger.debug('Starting batch file reading:', { count: paths.length });
const results: LocalReadFileResult[] = [];
for (const filePath of paths) {
logger.debug('Reading single file:', { filePath });
- const result = await readLocalFile({ path: filePath });
+ const result = await readLocalFile({ cwd, path: filePath });
results.push(result);
}
@@ -400,9 +400,9 @@ export default class LocalFileCtr extends ControllerModule {
}
@IpcMethod()
- async handleMoveFiles({ items }: MoveLocalFilesParams): Promise<LocalMoveFilesResultItem[]> {
+ async handleMoveFiles({ items, cwd }: MoveLocalFilesParams): Promise<LocalMoveFilesResultItem[]> {
logger.debug('Starting batch file move:', { itemsCount: items?.length });
- return moveLocalFiles({ items });
+ return moveLocalFiles({ cwd, items });
}
@IpcMethod()
@@ -418,9 +418,9 @@ export default class LocalFileCtr extends ControllerModule {
}
@IpcMethod()
- async handleWriteFile({ path: filePath, content }: WriteLocalFileParams) {
+ async handleWriteFile({ path: filePath, content, cwd }: WriteLocalFileParams) {
logger.debug(`Writing file ${filePath}`, { contentLength: content?.length });
- return writeLocalFile({ content, path: filePath });
+ return writeLocalFile({ content, cwd, path: filePath });
}
@IpcMethod()
diff --git a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
index d3eb5765ce9..4a56566e28d 100644
--- a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
@@ -2700,6 +2700,10 @@ export const createRuntimeExecutors = (
toolResultMaxLength,
topicId: ctx.topicId,
userId: ctx.userId,
+ // Device-bound cwd folded into deviceSystemInfo at operation
+ // creation; resume-safe via computeDeviceContext (recovers it
+ // from the prior tool message's pluginState.metadata).
+ workingDirectory: state.metadata?.deviceSystemInfo?.workingDirectory,
workspaceId: state.metadata?.workspaceId ?? ctx.workspaceId,
}),
{
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index d3ebe401e9f..faf8402d4f9 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -277,6 +277,22 @@ interface InternalExecAgentParams extends ExecAgentParams {
userInterventionConfig?: UserInterventionConfig;
}
+/**
+ * Result of {@link AiAgentService.resolveWorkspaceInit}: the cacheable scan
+ * (`workspace`) plus the per-run resolved bound directory (`boundCwd`).
+ *
+ * `boundCwd` is deliberately kept OUT of {@link WorkspaceInitResult}: that type
+ * is persisted into `devices.workingDirs[].workspace` and read by the web UI,
+ * and its scanned root is always the enclosing `WorkingDirEntry.path` β€” not a
+ * field on the scan. Surfacing it here lets the caller fill the system prompt's
+ * `{{workingDirectory}}` (and the tool cwd/scope downstream) without re-loading
+ * the device + topic the scan already read.
+ */
+interface ResolvedWorkspaceInit {
+ boundCwd?: string;
+ workspace: WorkspaceInitResult;
+}
+
/**
* AI Agent Service
*
@@ -370,18 +386,22 @@ export class AiAgentService {
activeDeviceId: string | undefined;
agencyConfig?: LobeAgentAgencyConfig;
topicId: string;
- }): Promise<WorkspaceInitResult> {
+ }): Promise<ResolvedWorkspaceInit> {
const empty: WorkspaceInitResult = { instructions: [], skills: [] };
const { activeDeviceId, agencyConfig, topicId } = params;
- if (!activeDeviceId) return empty;
+ if (!activeDeviceId) return { workspace: empty };
try {
const deviceModel = new DeviceModel(this.db, this.userId);
const device = await deviceModel.findByDeviceId(activeDeviceId);
- if (!device) return empty;
+ if (!device) return { workspace: empty };
// The bound project root we scan β€” resolved via the shared precedence
- // helper so it cannot drift from hetero dispatch / topic backfill.
+ // helper so it cannot drift from hetero dispatch / topic backfill. Read
+ // from the persisted `device.defaultCwd` (not a live device query, which
+ // only reports the daemon's process.cwd = `/`); also returned to the
+ // caller so the system prompt's {{workingDirectory}} reflects the same
+ // bound directory the workspace scan used.
const topic = await this.topicModel.findById(topicId);
const boundCwd = resolveDeviceWorkingDirectory({
deviceDefaultCwd: device.defaultCwd,
@@ -389,14 +409,14 @@ export class AiAgentService {
topicWorkingDirectory: topic?.metadata?.workingDirectory,
workingDirByDevice: agencyConfig?.workingDirByDevice,
});
- if (!boundCwd) return empty;
+ if (!boundCwd) return { workspace: empty };
const workingDirs = device.workingDirs ?? [];
const cached = workingDirs.find((dir) => dir.path === boundCwd);
if (isWorkspaceCacheFresh(cached, Date.now()) && cached?.workspace) {
log('execAgent: reusing cached workspace init for %s', boundCwd);
- return cached.workspace;
+ return { boundCwd, workspace: cached.workspace };
}
const scanned = await deviceGateway.initWorkspace({
@@ -409,9 +429,9 @@ export class AiAgentService {
// cache rather than dropping the project's skills + instructions.
if (cached?.workspace) {
log('execAgent: workspace init scan failed, using stale cache for %s', boundCwd);
- return cached.workspace;
+ return { boundCwd, workspace: cached.workspace };
}
- return empty;
+ return { boundCwd, workspace: empty };
}
// Persist the fresh scan back onto `workingDirs` (update in place or prepend
@@ -420,10 +440,10 @@ export class AiAgentService {
await deviceModel.update(activeDeviceId, { workingDirs: updated });
log('execAgent: scanned and cached workspace init for %s', boundCwd);
- return scanned;
+ return { boundCwd, workspace: scanned };
} catch (error) {
log('execAgent: resolveWorkspaceInit failed: %O', error);
- return empty;
+ return { workspace: empty };
}
}
@@ -2233,7 +2253,11 @@ export class AiAgentService {
platform: device?.platform ?? 'unknown',
userDataPath: systemInfo.userDataPath,
videosPath: systemInfo.videosPath,
- workingDirectory: systemInfo.workingDirectory,
+ // `workingDirectory` is intentionally NOT taken from the live device
+ // query β€” it only reports the daemon's process.cwd() (= `/` for a
+ // Finder/Dock-launched app). The bound directory is resolved from the
+ // persisted device row in resolveWorkspaceInit and written onto
+ // deviceSystemInfo.workingDirectory at the call site below.
};
} catch (error) {
log('execAgent: failed to fetch device system info: %O', error);
@@ -2655,7 +2679,17 @@ export class AiAgentService {
topicId,
});
- const projectMetas = workspaceInit.skills.map((s) => ({
+ // Feed the bound directory (resolved from the persisted device row) into
+ // the local-system tool's {{workingDirectory}} placeholder β€” the channel
+ // the model uses to know where it is and reach for absolute paths β€” and,
+ // downstream, the runCommand cwd / search scope (RuntimeExecutors reads
+ // state.metadata.deviceSystemInfo.workingDirectory). Resume-safe via the
+ // existing deviceSystemInfo plumbing (computeDeviceContext).
+ if (workspaceInit.boundCwd) {
+ deviceSystemInfo.workingDirectory = workspaceInit.boundCwd;
+ }
+
+ const projectMetas = workspaceInit.workspace.skills.map((s) => ({
description: s.description ?? '',
identifier: `project:${s.name}`,
location: s.path,
@@ -2675,8 +2709,8 @@ export class AiAgentService {
// trailing blocks on the system role β€” after the agent's persona and any
// page/task/additional instructions. `agentConfig` is read by
// `createOperation` below, so appending here still reaches the LLM.
- if (workspaceInit.instructions.length) {
- const block = workspaceInit.instructions
+ if (workspaceInit.workspace.instructions.length) {
+ const block = workspaceInit.workspace.instructions
.map(
({ content, source }) =>
`<project_instructions source="${source}">\n${content}\n</project_instructions>`,
@@ -2687,8 +2721,8 @@ export class AiAgentService {
: block;
log(
'execAgent: injected %d project instruction file(s): %s',
- workspaceInit.instructions.length,
- workspaceInit.instructions.map((i) => i.source).join(', '),
+ workspaceInit.workspace.instructions.length,
+ workspaceInit.workspace.instructions.map((i) => i.source).join(', '),
);
}
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
index e2a1967b67b..211fa69616b 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
@@ -1,4 +1,8 @@
-import { LocalSystemIdentifier, LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
+import {
+ LocalSystemApiName,
+ LocalSystemIdentifier,
+ LocalSystemManifest,
+} from '@lobechat/builtin-tool-local-system';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { type ToolExecutionContext } from '../../types';
@@ -114,4 +118,77 @@ describe('localSystemRuntime', () => {
);
});
});
+
+ describe('working directory injection', () => {
+ const parseArgs = () => JSON.parse(mockExecuteToolCall.mock.calls[0][1].arguments);
+
+ const buildProxy = (workingDirectory?: string) => {
+ mockExecuteToolCall.mockResolvedValue({ content: '', success: true });
+ return localSystemRuntime.factory({
+ activeDeviceId: 'device-1',
+ toolManifestMap: {},
+ userId: 'user-1',
+ workingDirectory,
+ });
+ };
+
+ it('injects cwd into runCommand when the model omits it', async () => {
+ const proxy = buildProxy('/Users/me/repo');
+ await proxy[LocalSystemApiName.runCommand]({ command: 'git status' });
+
+ expect(parseArgs()).toEqual({ command: 'git status', cwd: '/Users/me/repo' });
+ });
+
+ it('injects scope into search ops that honor it', async () => {
+ const proxy = buildProxy('/Users/me/repo');
+ await proxy[LocalSystemApiName.grepContent]({ pattern: 'TODO' });
+
+ expect(parseArgs()).toEqual({ pattern: 'TODO', scope: '/Users/me/repo' });
+ });
+
+ it('does not override an explicit cwd/scope 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' });
+ });
+
+ it('injects cwd into file ops so the daemon can resolve a relative path', async () => {
+ const proxy = buildProxy('/Users/me/repo');
+ await proxy[LocalSystemApiName.readFile]({ path: 'src/index.ts' });
+
+ // The daemon's resolveAgainstCwd anchors the relative path to cwd; an
+ // absolute path the model supplies passes through unchanged there.
+ expect(parseArgs()).toEqual({ cwd: '/Users/me/repo', path: 'src/index.ts' });
+ });
+
+ it('injects cwd into writeFile / editFile / moveFiles', async () => {
+ for (const api of [
+ LocalSystemApiName.writeFile,
+ LocalSystemApiName.editFile,
+ LocalSystemApiName.moveFiles,
+ ]) {
+ mockExecuteToolCall.mockClear();
+ const proxy = buildProxy('/Users/me/repo');
+ await proxy[api]({ path: 'x' });
+ expect(JSON.parse(mockExecuteToolCall.mock.calls[0][1].arguments).cwd).toBe(
+ '/Users/me/repo',
+ );
+ }
+ });
+
+ it('does not inject for command-id ops (getCommandOutput / killCommand)', async () => {
+ const proxy = buildProxy('/Users/me/repo');
+ await proxy[LocalSystemApiName.getCommandOutput]({ shell_id: 'cmd-1' });
+
+ expect(parseArgs()).toEqual({ shell_id: 'cmd-1' });
+ });
+
+ it('leaves args untouched when no working directory is bound', async () => {
+ const proxy = buildProxy(undefined);
+ await proxy[LocalSystemApiName.runCommand]({ command: 'pwd' });
+
+ expect(parseArgs()).toEqual({ command: 'pwd' });
+ });
+ });
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
index d3eb7c22008..c1b00355cc3 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
@@ -1,9 +1,44 @@
-import { LocalSystemIdentifier, LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
+import {
+ LocalSystemApiName,
+ LocalSystemIdentifier,
+ LocalSystemManifest,
+} from '@lobechat/builtin-tool-local-system';
import { deviceGateway } from '@/server/services/deviceGateway';
import { type ServerRuntimeRegistration } from './types';
+/**
+ * Which arg carries the working directory for the APIs that consume one. The
+ * model never picks the working directory β€” the system prompt's
+ * `{{workingDirectory}}` tells it where it is β€” so the runtime injects it as the
+ * tool call's cwd/scope. `executeToolCall` only forwards `arguments`, so it must
+ * ride in the args; the daemon otherwise falls back to `process.cwd()` (= `/`
+ * for a Finder/Dock-launched app):
+ *
+ * - `runCommand β†’ cwd`: the manifest deliberately hides `cwd`, but the daemon
+ * spawns in `params.cwd`.
+ * - file ops (`readFile`/`writeFile`/`editFile`/`moveFiles`) β†’ `cwd`:
+ * the daemon resolves a relative `path`/`file_path`/move item against
+ * `params.cwd` (see `resolveAgainstCwd`), so a model-supplied relative path
+ * lands in the bound directory instead of `/`. Absolute paths ignore it.
+ * - search ops (`searchFiles`/`globFiles`/`grepContent`) β†’ `scope`: their
+ * manifest claims `scope` "defaults to the working directory", but the daemon
+ * falls back to `process.cwd()`. Inject `scope` so that promise holds.
+ *
+ * APIs that act on a command id (getCommandOutput / killCommand) take neither.
+ */
+const WORKING_DIR_ARG: Partial<Record<string, 'cwd' | 'scope'>> = {
+ [LocalSystemApiName.editFile]: 'cwd',
+ [LocalSystemApiName.globFiles]: 'scope',
+ [LocalSystemApiName.grepContent]: 'scope',
+ [LocalSystemApiName.moveFiles]: 'cwd',
+ [LocalSystemApiName.readFile]: 'cwd',
+ [LocalSystemApiName.runCommand]: 'cwd',
+ [LocalSystemApiName.searchFiles]: 'scope',
+ [LocalSystemApiName.writeFile]: 'cwd',
+};
+
export const localSystemRuntime: ServerRuntimeRegistration = {
factory: (context) => {
if (!context.userId) {
@@ -16,7 +51,15 @@ export const localSystemRuntime: ServerRuntimeRegistration = {
const proxy: Record<string, (args: any) => Promise<any>> = {};
for (const api of LocalSystemManifest.api) {
+ const workingDirArg = WORKING_DIR_ARG[api.name];
proxy[api.name] = async (args: any) => {
+ // Inject the device-bound cwd/scope when the model didn't supply one.
+ // `??=` leaves an explicit per-call override possible for the future.
+ const finalArgs =
+ workingDirArg && context.workingDirectory && args?.[workingDirArg] == null
+ ? { ...args, [workingDirArg]: context.workingDirectory }
+ : args;
+
return deviceGateway.executeToolCall(
{
deviceId: context.activeDeviceId!,
@@ -25,7 +68,7 @@ export const localSystemRuntime: ServerRuntimeRegistration = {
},
{
apiName: api.name,
- arguments: JSON.stringify(args),
+ arguments: JSON.stringify(finalArgs),
identifier: LocalSystemIdentifier,
},
context.executionTimeoutMs,
diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.ts
index 74389b6a4d1..a9847a3bb44 100644
--- a/apps/server/src/services/toolExecution/types.ts
+++ b/apps/server/src/services/toolExecution/types.ts
@@ -185,6 +185,17 @@ export interface ToolExecutionContext {
/** Topic ID for sandbox session management */
topicId?: string;
userId?: string;
+ /**
+ * Device-bound working directory resolved when the operation was created
+ * (`resolveDeviceWorkingDirectory`: topic override > workingDirByDevice >
+ * device default). Injected by device-proxy runtimes as the tool call's
+ * cwd/scope so commands and file ops land in the bound directory instead of
+ * the daemon's `process.cwd()` (= `/` for a Finder/Dock-launched app).
+ *
+ * NOT the conversation `scope` above β€” that is the operation's thread/group
+ * scope and is unrelated to the filesystem working directory.
+ */
+ workingDirectory?: string;
/**
* Workspace ID that scopes ownership for any model/service the runtime
* instantiates. When unset the runtime falls back to personal mode
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index 8162d3150a2..d8fb46f6e58 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -21,6 +21,12 @@ export type ListLocalFileSortBy = 'name' | 'modifiedTime' | 'createdTime' | 'siz
export type ListLocalFileSortOrder = 'asc' | 'desc';
export interface ListLocalFileParams {
+ /**
+ * Working directory a relative `path` resolves against (the device-bound
+ * directory, injected by the server runtime β€” not model-supplied). Absolute
+ * paths ignore it; absent β†’ the daemon's process cwd.
+ */
+ cwd?: string;
/**
* Maximum number of files to return
* @default 100
@@ -59,6 +65,8 @@ export interface MoveLocalFileParams {
}
export interface MoveLocalFilesParams {
+ /** Working directory each item's relative paths resolve against. See {@link ListLocalFileParams.cwd}. */
+ cwd?: string;
items: MoveLocalFileParams[];
}
@@ -81,12 +89,16 @@ export interface RenameLocalFileResult {
}
export interface LocalReadFileParams {
+ /** Working directory a relative `path` resolves against. See {@link ListLocalFileParams.cwd}. */
+ cwd?: string;
fullContent?: boolean;
loc?: [number, number];
path: string;
}
export interface LocalReadFilesParams {
+ /** Working directory each relative path resolves against. See {@link ListLocalFileParams.cwd}. */
+ cwd?: string;
paths: string[];
}
@@ -95,6 +107,8 @@ export interface WriteLocalFileParams {
* Content to write
*/
content: string;
+ /** Working directory a relative `path` resolves against. See {@link ListLocalFileParams.cwd}. */
+ cwd?: string;
/**
* File path to write to
@@ -351,6 +365,8 @@ export interface GlobFilesResult {
// Edit types
export interface EditLocalFileParams {
+ /** Working directory a relative `file_path` resolves against. See {@link ListLocalFileParams.cwd}. */
+ cwd?: string;
file_path: string;
new_string: string;
old_string: string;
diff --git a/packages/local-file-shell/src/file/__tests__/resolveAgainstCwd.test.ts b/packages/local-file-shell/src/file/__tests__/resolveAgainstCwd.test.ts
new file mode 100644
index 00000000000..bc8393120f6
--- /dev/null
+++ b/packages/local-file-shell/src/file/__tests__/resolveAgainstCwd.test.ts
@@ -0,0 +1,33 @@
+import os from 'node:os';
+import path from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+import { resolveAgainstCwd } from '../expandTilde';
+
+describe('resolveAgainstCwd', () => {
+ const cwd = '/Users/me/repo';
+
+ it('anchors a relative path to cwd', () => {
+ expect(resolveAgainstCwd('src/index.ts', cwd)).toBe(path.join(cwd, 'src/index.ts'));
+ expect(resolveAgainstCwd('./pkg/a.ts', cwd)).toBe(path.join(cwd, 'pkg/a.ts'));
+ });
+
+ it('leaves an absolute path untouched', () => {
+ expect(resolveAgainstCwd('/etc/hosts', cwd)).toBe('/etc/hosts');
+ });
+
+ it('expands ~ before considering cwd', () => {
+ expect(resolveAgainstCwd('~/notes.md', cwd)).toBe(path.join(os.homedir(), 'notes.md'));
+ });
+
+ it('falls back to expandTilde behavior when cwd is absent (no regression)', () => {
+ expect(resolveAgainstCwd('src/index.ts')).toBe('src/index.ts');
+ expect(resolveAgainstCwd('src/index.ts', undefined)).toBe('src/index.ts');
+ });
+
+ it('passes through empty / undefined input', () => {
+ expect(resolveAgainstCwd(undefined, cwd)).toBeUndefined();
+ expect(resolveAgainstCwd('', cwd)).toBe('');
+ });
+});
diff --git a/packages/local-file-shell/src/file/edit.ts b/packages/local-file-shell/src/file/edit.ts
index bad4b26f77d..cceeb9d73f9 100644
--- a/packages/local-file-shell/src/file/edit.ts
+++ b/packages/local-file-shell/src/file/edit.ts
@@ -3,15 +3,16 @@ import { readFile, writeFile } from 'node:fs/promises';
import { createPatch } from 'diff';
import type { EditFileParams, EditFileResult } from '../types';
-import { expandTilde } from './expandTilde';
+import { resolveAgainstCwd } from './expandTilde';
export async function editLocalFile({
file_path: rawPath,
old_string,
new_string,
replace_all = false,
+ cwd,
}: EditFileParams): Promise<EditFileResult> {
- const filePath = expandTilde(rawPath) ?? rawPath;
+ const filePath = resolveAgainstCwd(rawPath, cwd) ?? rawPath;
try {
const content = await readFile(filePath, 'utf8');
diff --git a/packages/local-file-shell/src/file/expandTilde.ts b/packages/local-file-shell/src/file/expandTilde.ts
index 1085762c23c..1a72770f7b4 100644
--- a/packages/local-file-shell/src/file/expandTilde.ts
+++ b/packages/local-file-shell/src/file/expandTilde.ts
@@ -15,3 +15,23 @@ export const expandTilde = (input: string | undefined): string | undefined => {
}
return input;
};
+
+/**
+ * Resolve a filesystem path for Node fs APIs: first expand a leading `~`, then
+ * anchor a still-relative path to `cwd` β€” the device-bound working directory.
+ *
+ * Absolute paths pass through untouched. When `cwd` is absent the behavior is
+ * identical to {@link expandTilde}, so callers that don't carry a working
+ * directory (e.g. desktop client-mode today) keep resolving relative paths
+ * against the process cwd and nothing regresses. Without this, a relative path
+ * supplied by the model resolves against the daemon's `process.cwd()` (= `/`
+ * for a Finder/Dock-launched app) instead of the user's bound directory.
+ */
+export const resolveAgainstCwd = (
+ input: string | undefined,
+ cwd?: string,
+): string | undefined => {
+ const expanded = expandTilde(input);
+ if (!expanded || !cwd) return expanded;
+ return path.isAbsolute(expanded) ? expanded : path.join(cwd, expanded);
+};
diff --git a/packages/local-file-shell/src/file/list.ts b/packages/local-file-shell/src/file/list.ts
index 0ab81df44fe..a2b1230b3ce 100644
--- a/packages/local-file-shell/src/file/list.ts
+++ b/packages/local-file-shell/src/file/list.ts
@@ -4,7 +4,7 @@ import path from 'node:path';
import { SYSTEM_FILES_TO_IGNORE } from '@lobechat/file-loaders';
import type { FileEntry, ListFilesParams, ListFilesResult } from '../types';
-import { expandTilde } from './expandTilde';
+import { resolveAgainstCwd } from './expandTilde';
export interface ListFilesOptions {
/** Whether to filter out system files like .DS_Store, Thumbs.db, etc. */
@@ -12,11 +12,11 @@ export interface ListFilesOptions {
}
export async function listLocalFiles(
- { path: rawPath, sortBy = 'modifiedTime', sortOrder = 'desc', limit = 100 }: ListFilesParams,
+ { path: rawPath, sortBy = 'modifiedTime', sortOrder = 'desc', limit = 100, cwd }: ListFilesParams,
options?: ListFilesOptions,
): Promise<ListFilesResult> {
const { ignoreSystemFiles = true } = options || {};
- const dirPath = expandTilde(rawPath) ?? rawPath;
+ const dirPath = resolveAgainstCwd(rawPath, cwd) ?? rawPath;
try {
const entries = await readdir(dirPath);
diff --git a/packages/local-file-shell/src/file/move.ts b/packages/local-file-shell/src/file/move.ts
index 0f0bcbf124b..38222191e7c 100644
--- a/packages/local-file-shell/src/file/move.ts
+++ b/packages/local-file-shell/src/file/move.ts
@@ -3,9 +3,9 @@ import { access, mkdir, rename } from 'node:fs/promises';
import path from 'node:path';
import type { MoveFileResultItem, MoveFilesParams } from '../types';
-import { expandTilde } from './expandTilde';
+import { resolveAgainstCwd } from './expandTilde';
-export async function moveLocalFiles({ items }: MoveFilesParams): Promise<MoveFileResultItem[]> {
+export async function moveLocalFiles({ items, cwd }: MoveFilesParams): Promise<MoveFileResultItem[]> {
const results: MoveFileResultItem[] = [];
if (!items || items.length === 0) {
@@ -13,8 +13,8 @@ export async function moveLocalFiles({ items }: MoveFilesParams): Promise<MoveFi
}
for (const item of items) {
- const sourcePath = expandTilde(item.oldPath) ?? item.oldPath;
- const newPath = expandTilde(item.newPath) ?? item.newPath;
+ const sourcePath = resolveAgainstCwd(item.oldPath, cwd) ?? item.oldPath;
+ const newPath = resolveAgainstCwd(item.newPath, cwd) ?? item.newPath;
const resultItem: MoveFileResultItem = {
newPath: undefined,
sourcePath,
diff --git a/packages/local-file-shell/src/file/read.ts b/packages/local-file-shell/src/file/read.ts
index be16e6217fb..b40d54f3eca 100644
--- a/packages/local-file-shell/src/file/read.ts
+++ b/packages/local-file-shell/src/file/read.ts
@@ -9,7 +9,7 @@ import {
} from '@lobechat/file-loaders';
import type { ReadFileParams, ReadFileResult } from '../types';
-import { expandTilde } from './expandTilde';
+import { resolveAgainstCwd } from './expandTilde';
/** Hard cap on file size we will read into memory at all (10MB). */
const MAX_FILE_SIZE_BYTES = 10 * 1024 * 1024;
@@ -46,8 +46,9 @@ export async function readLocalFile({
path: rawPath,
loc,
fullContent,
+ cwd,
}: ReadFileParams): Promise<ReadFileResult> {
- const filePath = expandTilde(rawPath) ?? rawPath;
+ const filePath = resolveAgainstCwd(rawPath, cwd) ?? rawPath;
const effectiveLoc = fullContent ? undefined : (loc ?? [0, 200]);
let stats;
diff --git a/packages/local-file-shell/src/file/write.ts b/packages/local-file-shell/src/file/write.ts
index 9d484e155a3..c0aefa300b8 100644
--- a/packages/local-file-shell/src/file/write.ts
+++ b/packages/local-file-shell/src/file/write.ts
@@ -2,16 +2,17 @@ import { mkdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
import type { WriteFileParams, WriteFileResult } from '../types';
-import { expandTilde } from './expandTilde';
+import { resolveAgainstCwd } from './expandTilde';
export async function writeLocalFile({
path: rawPath,
content,
+ cwd,
}: WriteFileParams): Promise<WriteFileResult> {
if (!rawPath) return { error: 'Path cannot be empty', success: false };
if (content === undefined) return { error: 'Content cannot be empty', success: false };
- const filePath = expandTilde(rawPath) ?? rawPath;
+ const filePath = resolveAgainstCwd(rawPath, cwd) ?? rawPath;
try {
const dirname = path.dirname(filePath);
diff --git a/packages/local-file-shell/src/types.ts b/packages/local-file-shell/src/types.ts
index ff6c1b6a9d1..56233edb9f8 100644
--- a/packages/local-file-shell/src/types.ts
+++ b/packages/local-file-shell/src/types.ts
@@ -82,6 +82,12 @@ export interface KillCommandResult {
// ─── File Types ───
export interface ReadFileParams {
+ /**
+ * Working directory a relative `path` is resolved against (the device-bound
+ * directory, injected by the runtime). Absolute paths ignore it; absent β†’ the
+ * process cwd, as before.
+ */
+ cwd?: string;
fullContent?: boolean;
loc?: [number, number];
path: string;
@@ -106,6 +112,8 @@ export interface ReadFileResult {
export interface WriteFileParams {
content: string;
+ /** Working directory a relative `path` resolves against. See {@link ReadFileParams.cwd}. */
+ cwd?: string;
path: string;
}
@@ -115,6 +123,8 @@ export interface WriteFileResult {
}
export interface EditFileParams {
+ /** Working directory a relative `file_path` resolves against. See {@link ReadFileParams.cwd}. */
+ cwd?: string;
file_path: string;
new_string: string;
old_string: string;
@@ -131,6 +141,8 @@ export interface EditFileResult {
}
export interface ListFilesParams {
+ /** Working directory a relative `path` resolves against. See {@link ReadFileParams.cwd}. */
+ cwd?: string;
limit?: number;
path: string;
sortBy?: 'createdTime' | 'modifiedTime' | 'name' | 'size';
@@ -232,6 +244,11 @@ export interface MoveFileItem {
}
export interface MoveFilesParams {
+ /**
+ * Working directory each item's relative `oldPath`/`newPath` resolves against.
+ * See {@link ReadFileParams.cwd}.
+ */
+ cwd?: string;
items: MoveFileItem[];
}