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(skills): run execScript inside the Local Sandbox fence (#22540)

Lobehub Coderb4a1bfddd1d1
diff --git a/apps/desktop/src/main/controllers/ShellCommandCtr.ts b/apps/desktop/src/main/controllers/ShellCommandCtr.ts
index 57df4ba338a..618347d41f3 100644
--- a/apps/desktop/src/main/controllers/ShellCommandCtr.ts
+++ b/apps/desktop/src/main/controllers/ShellCommandCtr.ts
@@ -298,8 +298,11 @@ export default class ShellCommandCtr extends ControllerModule {
// client executor via the runtime's `trustArgsCwd: false` path. This
// process cannot re-check that (it has no idea which directory the agent
// was configured with), so the guarantee is pinned by tests on both
- // injection sites instead.
- if (!params.cwd) {
+ // injection sites instead. A caller that runs from a different directory
+ // than the one it fences (skill scripts) names the fence in `sandboxRoot`,
+ // which both runCommand injection sites strip from model args the same way.
+ const fenceRoot = params.sandboxRoot ?? params.cwd;
+ if (!fenceRoot) {
return {
error:
'Local Sandbox requires a working directory. Set one for this agent (or topic) and run the command again.',
@@ -331,7 +334,7 @@ export default class ShellCommandCtr extends ControllerModule {
onSandboxUnavailable: (error) => this.downgradeSandboxCapability(error),
processManager,
spawnProcess,
- sandboxPolicy: createLocalSandboxPolicy(params.cwd, {
+ sandboxPolicy: createLocalSandboxPolicy(fenceRoot, {
allowNetwork: params.sandboxNetwork === true,
}),
});
diff --git a/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
index 0621631a7f9..184c7c12407 100644
--- a/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
@@ -370,6 +370,31 @@ describe('ShellCommandCtr (thin wrapper)', () => {
);
});
+ it('fences to an explicit sandboxRoot while running from cwd', async () => {
+ // Skill scripts start in the shared skill cache, which must stay outside
+ // the fence; their caller names the run's working directory instead.
+ mockProcessOutput = 'output\n';
+ setTimeout(() => {
+ mockChildProcess.exitCode = 0;
+ emitChildProcess('exit', 0);
+ emitChildProcess('close', 0);
+ }, 10);
+
+ await ctr.handleRunCommand({
+ command: 'echo test',
+ cwd: '/skills/extracted/hash',
+ sandbox: true,
+ sandboxRoot: '/repo',
+ });
+
+ expect(mockCreateSandboxLaunchPlan).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cwd: '/skills/extracted/hash',
+ policy: expect.objectContaining({ writableRoots: ['/repo'] }),
+ }),
+ );
+ });
+
it('refuses a sandboxed run with no working directory to confine', async () => {
// Falling back to process.cwd() would fence the app install directory and
// still report success β€” a guarantee about the wrong place.
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 6f1c39090ce..1f3704ac0cc 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
@@ -303,6 +303,26 @@ describe('localSystemRuntime', () => {
expect(parseArgs().sandbox).toBe(true);
});
+ it('never lets a model-supplied sandboxRoot move the fence', async () => {
+ // `sandboxRoot` overrides the fence root on the device; only the skills
+ // runtime may set it, so a guessed one is dropped like a guessed `cwd`.
+ mockExecuteToolCall.mockResolvedValue({ content: '', success: true });
+ const proxy = localSystemRuntime.factory({
+ activeDeviceId: 'device-1',
+ localSandbox: true,
+ toolManifestMap: {},
+ userId: 'user-1',
+ workingDirectory: '/Users/me/repo',
+ });
+ await proxy[LocalSystemApiName.runCommand]({
+ command: 'echo owned > ~/.zshrc',
+ sandboxRoot: '/Users/me',
+ } as never);
+
+ expect(parseArgs()).not.toHaveProperty('sandboxRoot');
+ expect(parseArgs().sandbox).toBe(true);
+ });
+
it('forwards the network allowance for a fenced run', async () => {
mockExecuteToolCall.mockResolvedValue({ content: '', success: true });
const proxy = localSystemRuntime.factory({
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.localSandbox.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.localSandbox.test.ts
new file mode 100644
index 00000000000..1655142012c
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.localSandbox.test.ts
@@ -0,0 +1,275 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => {
+ const sandboxService = {
+ callTool: vi.fn(),
+ capabilities: {
+ backgroundCommands: true,
+ exportFile: true,
+ files: true,
+ languages: ['python'],
+ persistentSession: true,
+ shell: true,
+ skillScripts: true,
+ },
+ exportAndUploadFile: vi.fn(),
+ kind: 'onlyboxes',
+ };
+
+ return {
+ buildDeviceLhEnv: vi.fn(),
+ checkHash: vi.fn(),
+ createSandboxService: vi.fn(function () {
+ return sandboxService;
+ }),
+ executeToolCall: vi.fn(),
+ fileService: {
+ getFullFileUrl: vi.fn(),
+ },
+ findAll: vi.fn(),
+ findById: vi.fn(),
+ findByName: vi.fn(),
+ isLhCommand: vi.fn(),
+ getAgentConfigById: vi.fn(),
+ getAgentSkills: vi.fn(),
+ getUserSettings: vi.fn(),
+ marketService: {},
+ prepareSkillDirectory: vi.fn(),
+ preprocessLhCommand: vi.fn(),
+ readResource: vi.fn(),
+ resolveContentWorkspaceId: vi.fn(),
+ resolveRunWorkspaceId: vi.fn(),
+ sandboxService,
+ };
+});
+
+vi.mock('@lobechat/builtin-skills', () => ({
+ builtinSkills: [],
+}));
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn(function () {
+ return {
+ getAgentConfigById: mocks.getAgentConfigById,
+ };
+ }),
+}));
+
+vi.mock('@/database/models/agentSkill', () => ({
+ AgentSkillModel: vi.fn(function () {
+ return {
+ findAll: mocks.findAll,
+ findById: mocks.findById,
+ findByName: mocks.findByName,
+ };
+ }),
+}));
+
+vi.mock('@/database/models/file', () => ({
+ FileModel: vi.fn(function () {
+ return {
+ checkHash: mocks.checkHash,
+ };
+ }),
+}));
+
+vi.mock('@/database/models/user', () => ({
+ UserModel: vi.fn(function () {
+ return {
+ getUserSettings: mocks.getUserSettings,
+ };
+ }),
+}));
+
+vi.mock('@/helpers/skillFilters', () => ({
+ filterBuiltinSkills: vi.fn(function (skills: unknown) {
+ return skills;
+ }),
+}));
+
+vi.mock('@/server/services/agentDocuments', () => ({
+ AgentDocumentsService: vi.fn(function () {
+ return {
+ getAgentSkills: mocks.getAgentSkills,
+ };
+ }),
+}));
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn(function () {
+ return mocks.fileService;
+ }),
+}));
+
+vi.mock('@/server/services/market', () => ({
+ MarketService: vi.fn(function () {
+ return mocks.marketService;
+ }),
+}));
+
+vi.mock('@/server/services/sandbox', async () => {
+ const actual = await vi.importActual('@/server/services/sandbox');
+
+ return {
+ ...(actual as Record<string, unknown>),
+ createSandboxService: mocks.createSandboxService,
+ };
+});
+
+vi.mock('@/server/services/skill/resource', () => ({
+ SkillResourceService: vi.fn(function () {
+ return {
+ readResource: mocks.readResource,
+ };
+ }),
+}));
+
+vi.mock('@/server/services/toolExecution/preprocessLhCommand', () => ({
+ buildDeviceLhEnv: mocks.buildDeviceLhEnv,
+ isLhCommand: mocks.isLhCommand,
+ preprocessLhCommand: mocks.preprocessLhCommand,
+}));
+
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: {
+ prepareSkillDirectory: mocks.prepareSkillDirectory,
+ },
+}));
+
+vi.mock('@/server/services/deviceGateway/authorizedToolCall', () => ({
+ executeAuthorizedDeviceToolCall: (_serverDB: unknown, ...args: unknown[]) =>
+ mocks.executeToolCall(...args),
+}));
+
+vi.mock('../resolveWorkspaceScope', () => ({
+ resolveContentWorkspaceId: mocks.resolveContentWorkspaceId,
+ resolveRunWorkspaceId: mocks.resolveRunWorkspaceId,
+}));
+
+const EXTRACTED_DIR = '/home/user/.lobehub/skills/extracted/zip-hash-1';
+const WORKING_DIR = '/home/user/LobeHub/sandbox/agent-1';
+
+const runOnDevice = async (context: {
+ localSandbox?: boolean;
+ localSandboxNetwork?: boolean;
+ workingDirectory?: string;
+}) => {
+ const { skillsRuntime } = await import('../skills');
+ const runtime = await skillsRuntime.factory({
+ activeDeviceId: 'device-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ workingDirectory: WORKING_DIR,
+ ...context,
+ });
+
+ return runtime.execScript({
+ activatedSkills: [{ id: 'user-skill-id', name: 'user-skill' }],
+ command: 'echo hi > /etc/owned',
+ // A model-supplied fence switch or root must be ignored.
+ ...({ cwd: '/', sandbox: false } as object),
+ description: 'Write outside the skill directory',
+ });
+};
+
+const dispatchedArgs = () =>
+ JSON.parse(mocks.executeToolCall.mock.calls[0][1].arguments) as Record<string, unknown>;
+
+describe('skillsRuntime execScript Local Sandbox fence (device path)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ mocks.checkHash.mockResolvedValue({ isExist: true, url: 'skills/user-skill.zip' });
+ mocks.fileService.getFullFileUrl.mockResolvedValue('https://files.example.com/user-skill.zip');
+ mocks.findAll.mockResolvedValue({ data: [], total: 0 });
+ mocks.findById.mockResolvedValue(undefined);
+ mocks.getAgentConfigById.mockResolvedValue(undefined);
+ mocks.findByName.mockImplementation(async (name: string) =>
+ name === 'user-skill'
+ ? { id: 'user-skill-id', name: 'user-skill', zipFileHash: 'zip-hash-1' }
+ : undefined,
+ );
+ mocks.getAgentSkills.mockResolvedValue([]);
+ mocks.getUserSettings.mockResolvedValue({ market: { accessToken: 'market-token' } });
+ mocks.preprocessLhCommand.mockImplementation(async (command: string) => ({
+ command,
+ isLhCommand: false,
+ skipSkillLookup: false,
+ }));
+ mocks.isLhCommand.mockReturnValue(false);
+ mocks.buildDeviceLhEnv.mockReturnValue(undefined);
+ mocks.resolveContentWorkspaceId.mockImplementation(
+ async (ctx?: { workspaceId?: string }) => ctx?.workspaceId,
+ );
+ mocks.resolveRunWorkspaceId.mockResolvedValue(undefined);
+ mocks.prepareSkillDirectory.mockResolvedValue({ extractedDir: EXTRACTED_DIR, success: true });
+ mocks.executeToolCall.mockResolvedValue({
+ content: 'ok',
+ state: { exitCode: 0, stdout: 'ok', success: true },
+ success: true,
+ });
+ });
+
+ it('runs from the extracted skill directory but fences to the working directory', async () => {
+ // The extracted directory is the device's shared skill cache: fencing to it
+ // would let a fenced run plant code that a later unfenced run executes.
+ await runOnDevice({ localSandbox: true, localSandboxNetwork: true });
+
+ expect(dispatchedArgs()).toEqual({
+ command: 'echo hi > /etc/owned',
+ cwd: EXTRACTED_DIR,
+ sandbox: true,
+ sandboxNetwork: true,
+ sandboxRoot: WORKING_DIR,
+ });
+ }, 30_000);
+
+ it('refuses a fenced run with no working directory instead of fencing the skill cache', async () => {
+ const result = await runOnDevice({ localSandbox: true, workingDirectory: undefined });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('requires a working directory');
+ expect(mocks.executeToolCall).not.toHaveBeenCalled();
+ });
+
+ it('keeps the registry network closed unless the run allowed it', async () => {
+ await runOnDevice({ localSandbox: true });
+
+ expect(dispatchedArgs()).toMatchObject({ sandbox: true, sandboxNetwork: false });
+ });
+
+ it('reports the device sandbox refusal instead of a silent success', async () => {
+ mocks.executeToolCall.mockResolvedValue({
+ content: '',
+ state: {
+ exitCode: 1,
+ stderr: 'bash: /etc/owned: Operation not permitted',
+ success: false,
+ },
+ success: true,
+ });
+
+ const result = await runOnDevice({ localSandbox: true });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('Operation not permitted');
+ });
+
+ it('pins sandbox off for a local run that did not opt in', async () => {
+ await runOnDevice({ localSandbox: false });
+
+ expect(dispatchedArgs()).toEqual({
+ command: 'echo hi > /etc/owned',
+ cwd: EXTRACTED_DIR,
+ sandbox: false,
+ });
+ });
+
+ it('leaves the dispatch untouched when the run carries no sandbox decision', async () => {
+ await runOnDevice({});
+
+ expect(dispatchedArgs()).toEqual({ command: 'echo hi > /etc/owned', cwd: EXTRACTED_DIR });
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
index 5f368374fe4..154e311017b 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
@@ -136,7 +136,17 @@ export const localSystemRuntime: ServerRuntimeRegistration = {
// it: `lh goal plan` and the other run-attributed commands need it. The
// model's own `env` wins: it may be deliberately overriding the scope.
if (api.name === LocalSystemApiName.runCommand && typeof finalArgs?.command === 'string') {
- finalArgs = { ...finalArgs, topicId: context.topicId, agentId: context.agentId };
+ // `sandboxRoot` moves the fence; like `sandbox` below it is host-owned
+ // (only the skills runtime sets it), so a model-supplied one is dropped.
+ const { sandboxRoot: _offContractSandboxRoot, ...commandArgs } = finalArgs as Record<
+ string,
+ unknown
+ >;
+ finalArgs = {
+ ...(commandArgs as typeof finalArgs),
+ topicId: context.topicId,
+ agentId: context.agentId,
+ };
const lhEnv = buildDeviceLhEnv({
operationId: context.operationId,
workspaceId: await getContentWorkspaceId(),
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
index 2d315c36482..7af968ec398 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
@@ -108,6 +108,13 @@ interface UserSettingsWithMarketToken {
interface SkillDeviceExecution {
deviceId: string;
executionTimeoutMs?: number;
+ /**
+ * The run's resolved Local Sandbox decision (`context.localSandbox`), the
+ * same value the local-system device-proxy applies to `runCommand`.
+ */
+ localSandbox?: boolean;
+ /** `context.localSandboxNetwork`; only meaningful with {@link localSandbox}. */
+ localSandboxNetwork?: boolean;
operationId?: string;
/**
* Filesystem skills already living on the device (project/device SKILL.md).
@@ -593,6 +600,14 @@ class SkillServerRuntimeService implements SkillRuntimeService {
}
const cwd = runDir ?? device.workingDirectory;
+ // A fenced run writes only to the agent's working directory: `runDir` is
+ // the device's shared skill cache, which must stay out of the fence so a
+ // fenced run cannot plant code a later unfenced run executes.
+ if (device.localSandbox && !device.workingDirectory) {
+ return fail(
+ 'Local Sandbox requires a working directory. Set one for this agent (or topic) and run the command again.',
+ );
+ }
// Content scope, NOT the gateway-addressing scope resolved above: a
// workspace agent routed to the caller's own machine is still editing
// workspace content.
@@ -620,6 +635,17 @@ class SkillServerRuntimeService implements SkillRuntimeService {
// device credentials' personal scope, and tell it which run it acts for.
...(deviceLhEnv && { env: deviceLhEnv }),
...(device.executionTimeoutMs && { timeout: device.executionTimeoutMs }),
+ // The fence is the run owner's decision, applied exactly as the
+ // local-system device-proxy does for `runCommand`; neither it nor
+ // its root comes from the model. A client predating `sandboxRoot`
+ // still fences, just to `cwd`.
+ ...(device.localSandbox !== undefined && {
+ sandbox: device.localSandbox,
+ ...(device.localSandbox && {
+ sandboxNetwork: device.localSandboxNetwork === true,
+ sandboxRoot: device.workingDirectory,
+ }),
+ }),
}),
identifier: LocalSystemIdentifier,
},
@@ -973,6 +999,8 @@ export const skillsRuntime: ServerRuntimeRegistration = {
? {
deviceId: context.activeDeviceId,
executionTimeoutMs: context.executionTimeoutMs,
+ localSandbox: context.localSandbox,
+ localSandboxNetwork: context.localSandboxNetwork,
operationId: context.operationId,
projectSkills: context.projectSkills,
// Same lazy workspace-principal recovery as the local-system runtime,
diff --git a/packages/builtin-tool-local-system/src/client/executor/index.test.ts b/packages/builtin-tool-local-system/src/client/executor/index.test.ts
index e4148d31fb6..82d70ad8a53 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
@@ -278,6 +278,17 @@ describe('LocalSystemExecutor.runCommand', () => {
expect(args).not.toHaveProperty('sandboxNetwork');
});
+ it('drops a model-supplied sandboxRoot so the model cannot move its fence', async () => {
+ await localSystemExecutor.runCommand(
+ { command: 'echo owned > ~/.zshrc', sandboxRoot: '/Users/me' } as never,
+ { localSandbox: true, messageId: 'm-1', workingDirectory: '/repo' },
+ );
+
+ const args = runCommandMock.mock.calls[0][0];
+ expect(args).not.toHaveProperty('sandboxRoot');
+ expect(args).toMatchObject({ cwd: '/repo', sandbox: true });
+ });
+
it('never lets the model pick what it is fenced to', async () => {
// The runtime drops an args-supplied `cwd` while `trustArgsCwd` is off, and
// the sandbox roots itself at that same cwd β€” so a model that guesses the
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 554656c8310..05e32238bb9 100644
--- a/packages/builtin-tool-local-system/src/client/executor/index.ts
+++ b/packages/builtin-tool-local-system/src/client/executor/index.ts
@@ -145,15 +145,21 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {
// expose it in. The runtime anchors `cwd` to `ctx.workingDirectory` (and
// refuses the model's own `cwd` while `trustArgsCwd` is off), which is exactly
// the root the fence needs: a model must not get to choose what it is fenced
- // to. An unfenced command adds neither field and behaves as before.
- runCommand = (params: RunCommandParams, ctx?: BuiltinToolContext) =>
- this.execute(
+ // to. An unfenced command adds neither field and behaves as before. The
+ // host-only `sandboxRoot` override is dropped for the same reason: a model
+ // that guessed it could otherwise move its own fence.
+ runCommand = (params: RunCommandParams, ctx?: BuiltinToolContext) => {
+ const { sandboxRoot: _offContractSandboxRoot, ...modelParams } = params as RunCommandParams & {
+ sandboxRoot?: unknown;
+ };
+ return this.execute(
'runCommand',
ctx?.localSandbox === true
- ? { ...params, sandbox: true, sandboxNetwork: ctx?.localSandboxNetwork === true }
- : params,
+ ? { ...modelParams, sandbox: true, sandboxNetwork: ctx?.localSandboxNetwork === true }
+ : modelParams,
ctx,
);
+ };
getCommandOutput = (params: GetCommandOutputParams, ctx?: BuiltinToolContext) =>
this.execute('getCommandOutput', params, ctx);
diff --git a/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts b/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts
index 69327434ea4..f7ed2d901b5 100644
--- a/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts
@@ -44,10 +44,31 @@ export interface ExportFileResult {
url?: string;
}
+/**
+ * Host-resolved execution settings for one `execScript` call. Supplied by the
+ * caller that owns the run (the client executor from its tool context), never
+ * by the model β€” the manifest exposes none of these.
+ */
+export interface ExecScriptExecutionOptions {
+ /**
+ * Confine the command in the device sandbox (the "Local Sandbox" execution
+ * environment), with the same semantics as `local-system.runCommand`.
+ */
+ localSandbox?: boolean;
+ /** Let a fenced command reach the package-registry allowlist. */
+ localSandboxNetwork?: boolean;
+ /**
+ * The agent's working directory: the fence root of a sandboxed run (the
+ * skill directory is the shared skill cache and stays outside the fence),
+ * and its cwd when no skill directory resolves.
+ */
+ workingDirectory?: string;
+}
+
export interface SkillRuntimeService {
execScript?: (
command: string,
- options: {
+ options: ExecScriptExecutionOptions & {
activatedSkills?: Array<{ description?: string; id?: string; name: string }>;
description: string;
},
@@ -194,7 +215,10 @@ export class SkillsExecutionRuntime {
return resolved;
};
- async execScript(args: ExecScriptParams): Promise<BuiltinServerRuntimeOutput> {
+ async execScript(
+ args: ExecScriptParams,
+ execution?: ExecScriptExecutionOptions,
+ ): Promise<BuiltinServerRuntimeOutput> {
const { command, description } = args;
// Args win when the caller (client executor) already injected stepContext;
// the constructor option covers the server path where args are raw LLM output.
@@ -204,6 +228,7 @@ export class SkillsExecutionRuntime {
if (this.service.execScript) {
try {
const result = await this.service.execScript(command, {
+ ...execution,
activatedSkills,
description,
});
diff --git a/packages/builtin-tool-skills/src/executor/index.ts b/packages/builtin-tool-skills/src/executor/index.ts
index ef88d103201..760eb01c8cd 100644
--- a/packages/builtin-tool-skills/src/executor/index.ts
+++ b/packages/builtin-tool-skills/src/executor/index.ts
@@ -35,14 +35,25 @@ class SkillsExecutor extends BaseExecutor<typeof SkillsApiName> {
// Server will resolve zipUrls for all activated skills
const activatedSkills = ctx.stepContext?.activatedSkills;
- const result = await this.runtime.execScript({
- ...params,
- activatedSkills: activatedSkills?.map((s) => ({
- description: s.description,
- id: s.id,
- name: s.name,
- })),
- });
+ const result = await this.runtime.execScript(
+ {
+ ...params,
+ activatedSkills: activatedSkills?.map((s) => ({
+ description: s.description,
+ id: s.id,
+ name: s.name,
+ })),
+ },
+ // The fence is the run owner's decision, resolved into ctx by the
+ // caller exactly as for `local-system.runCommand` β€” never from params.
+ ctx.localSandbox === true
+ ? {
+ localSandbox: true,
+ localSandboxNetwork: ctx.localSandboxNetwork === true,
+ workingDirectory: ctx.workingDirectory,
+ }
+ : undefined,
+ );
if (result.success) {
return { content: result.content, state: result.state, success: true };
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index e20f90aa8df..91e775689d1 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -457,6 +457,16 @@ export interface RunCommandParams {
* registries and forges and nothing else.
*/
sandboxNetwork?: boolean;
+ /**
+ * The directory a sandboxed command may write to, when it differs from
+ * `cwd`. Ignored unless `sandbox` is true; absent means the fence is `cwd`.
+ * Skill scripts set it: they run from the device's shared skill cache, which
+ * must stay out of the fence (a fenced run could otherwise plant code that a
+ * later unfenced run executes), so the fence is the run's working directory
+ * instead. Host-owned like `sandbox` β€” both injection sites strip a
+ * model-supplied value.
+ */
+ sandboxRoot?: string;
timeout?: number;
topicId?: string;
}
diff --git a/src/store/tool/slices/builtin/executors/__tests__/lobe-skills.desktop.test.ts b/src/store/tool/slices/builtin/executors/__tests__/lobe-skills.desktop.test.ts
new file mode 100644
index 00000000000..8378eb62fb5
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/__tests__/lobe-skills.desktop.test.ts
@@ -0,0 +1,112 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { desktopSkillRuntimeService } from '@/services/electron/desktopSkillRuntime';
+import { localFileService } from '@/services/electron/localFileService';
+
+import { skillsExecutor } from '../lobe-skills.desktop';
+
+vi.mock('@lobechat/builtin-skills', () => ({ builtinSkills: [] }));
+vi.mock('@/helpers/skillFilters', () => ({ filterBuiltinSkills: () => [] }));
+vi.mock('@/services/skill', () => ({ agentSkillService: {} }));
+vi.mock('@/services/electron/desktopSkillRuntime', () => ({
+ desktopSkillRuntimeService: {
+ resolveExecutionDirectory: vi.fn(),
+ resolveReferenceFullPath: vi.fn(),
+ },
+}));
+vi.mock('@/services/electron/localFileService', () => ({
+ localFileService: { runCommand: vi.fn() },
+}));
+
+const SKILL_DIR = '/Users/me/.lobehub/skills/pdf';
+const WORKING_DIR = '/Users/me/LobeHub/sandbox/agent-1';
+
+const execScript = (ctx: Record<string, unknown> = {}) =>
+ skillsExecutor.invoke(
+ 'execScript',
+ { command: 'echo hi > /etc/owned', description: 'Write outside' },
+ { messageId: 'test-message', workingDirectory: WORKING_DIR, ...ctx },
+ );
+
+describe('Desktop Skills execScript Local Sandbox fence', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(localFileService.runCommand).mockResolvedValue({
+ exit_code: 0,
+ stdout: 'ok',
+ success: true,
+ } as any);
+ });
+
+ it('runs from the skill directory but fences to the working directory', async () => {
+ // The skill directory is the shared skill cache: writable, a fenced run
+ // could plant code that a later unfenced run executes.
+ vi.mocked(desktopSkillRuntimeService.resolveExecutionDirectory).mockResolvedValue(SKILL_DIR);
+
+ await execScript({ localSandbox: true, localSandboxNetwork: true });
+
+ expect(localFileService.runCommand).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cwd: SKILL_DIR,
+ sandbox: true,
+ sandboxNetwork: true,
+ sandboxRoot: WORKING_DIR,
+ }),
+ );
+ });
+
+ it('runs from the working directory when no skill directory resolves', async () => {
+ vi.mocked(desktopSkillRuntimeService.resolveExecutionDirectory).mockResolvedValue(undefined);
+
+ await execScript({ localSandbox: true });
+
+ expect(localFileService.runCommand).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cwd: WORKING_DIR,
+ sandbox: true,
+ sandboxNetwork: false,
+ sandboxRoot: WORKING_DIR,
+ }),
+ );
+ });
+
+ it('refuses a fenced run with no working directory instead of fencing the skill cache', async () => {
+ vi.mocked(desktopSkillRuntimeService.resolveExecutionDirectory).mockResolvedValue(SKILL_DIR);
+
+ const result = await execScript({ localSandbox: true, workingDirectory: undefined });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('requires a working directory');
+ expect(localFileService.runCommand).not.toHaveBeenCalled();
+ });
+
+ it('surfaces the sandbox refusal instead of reporting success', async () => {
+ vi.mocked(desktopSkillRuntimeService.resolveExecutionDirectory).mockResolvedValue(SKILL_DIR);
+ vi.mocked(localFileService.runCommand).mockResolvedValue({
+ exit_code: 1,
+ stderr: 'bash: /etc/owned: Operation not permitted',
+ success: false,
+ } as any);
+
+ const result = await execScript({ localSandbox: true });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('Operation not permitted');
+ });
+
+ it.each([
+ ['off', { localSandbox: false }],
+ ['unset', {}],
+ ])('keeps the unfenced command unchanged when Local Sandbox is %s', async (_, ctx) => {
+ vi.mocked(desktopSkillRuntimeService.resolveExecutionDirectory).mockResolvedValue(undefined);
+
+ await execScript(ctx);
+
+ const params = vi.mocked(localFileService.runCommand).mock.calls[0][0];
+ expect(params).not.toHaveProperty('sandbox');
+ expect(params).not.toHaveProperty('sandboxNetwork');
+ expect(params).not.toHaveProperty('sandboxRoot');
+ // No working-directory fallback either: the historical cwd is the skill dir only.
+ expect(params.cwd).toBeUndefined();
+ });
+});
diff --git a/src/store/tool/slices/builtin/executors/lobe-skills.desktop.ts b/src/store/tool/slices/builtin/executors/lobe-skills.desktop.ts
index 27d17863c1a..7ec38e68ecc 100644
--- a/src/store/tool/slices/builtin/executors/lobe-skills.desktop.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-skills.desktop.ts
@@ -17,13 +17,33 @@ const runtime = new SkillsExecutionRuntime({
builtinSkills: filterBuiltinSkills(builtinSkills),
service: {
execScript: async (command, options) => {
- const cwd = await desktopSkillRuntimeService.resolveExecutionDirectory(
+ const skillDir = await desktopSkillRuntimeService.resolveExecutionDirectory(
options.activatedSkills,
);
+ // A Local Sandbox run is fenced to the agent's working directory, never
+ // to the skill directory: that is the device's shared skill cache, and a
+ // writable cache would let a fenced run plant code a later unfenced run
+ // executes. The script still starts in its skill directory (reads are not
+ // fenced). Unfenced runs keep the historical skill-directory-only cwd.
+ if (options.localSandbox && !options.workingDirectory) {
+ return {
+ executionEnv: 'device' as const,
+ exitCode: 1,
+ output: '',
+ stderr:
+ 'Local Sandbox requires a working directory. Set one for this agent (or topic) and run the command again.',
+ success: false,
+ };
+ }
const result = await localFileService.runCommand({
command,
- cwd,
+ cwd: options.localSandbox ? (skillDir ?? options.workingDirectory) : skillDir,
description: options.description,
+ ...(options.localSandbox && {
+ sandbox: true,
+ sandboxNetwork: options.localSandboxNetwork === true,
+ sandboxRoot: options.workingDirectory,
+ }),
timeout: undefined,
});
return {