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.

โœจ feat(device): add a Local Sandbox execution environment (#18143)

LiJiane9b6d00ab3bb
diff --git a/apps/desktop/electron-builder.mjs b/apps/desktop/electron-builder.mjs
index 753fa408ef3..b38bdd866cc 100644
--- a/apps/desktop/electron-builder.mjs
+++ b/apps/desktop/electron-builder.mjs
@@ -290,6 +290,20 @@ const config = {
extraResources: [
{ from: 'resources/bin', to: 'bin' },
{ from: 'resources/cli-package.json', to: 'package.json' },
+ // Local Sandbox helper binaries. The sandbox spawns these by path, so they
+ // must be real files โ€” not entries inside app.asar, and not something the
+ // user is expected to install separately.
+ //
+ // Shipped as a resource rather than by externalizing
+ // `@anthropic-ai/sandbox-runtime`: its JavaScript bundles into the main
+ // process perfectly well, and making it a production dependency instead
+ // drags four transitive packages into electron-builder's node_modules
+ // traversal, which pnpm's layout does not satisfy (`@pondwader/socks5-server
+ // not found`). Only the binaries need to exist on disk.
+ {
+ from: 'node_modules/@anthropic-ai/sandbox-runtime/vendor',
+ to: 'sandbox-runtime/vendor',
+ },
],
win: {
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 1d058ada7cb..0d8904cb376 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -54,6 +54,7 @@
"node-screenshots": "^0.2.8"
},
"devDependencies": {
+ "@anthropic-ai/sandbox-runtime": "0.0.66",
"@base-ui/react": "^1.6.0",
"@electron-toolkit/eslint-config-prettier": "^3.0.0",
"@electron-toolkit/eslint-config-ts": "^3.1.0",
@@ -65,6 +66,7 @@
"@lobechat/device-control": "workspace:*",
"@lobechat/device-gateway-client": "workspace:*",
"@lobechat/device-identity": "workspace:*",
+ "@lobechat/device-sandbox": "workspace:*",
"@lobechat/electron-client-ipc": "workspace:*",
"@lobechat/electron-server-ipc": "workspace:*",
"@lobechat/file-loaders": "workspace:*",
diff --git a/apps/desktop/src/main/controllers/ShellCommandCtr.ts b/apps/desktop/src/main/controllers/ShellCommandCtr.ts
index cb2f73d98b7..3dcd7a0a603 100644
--- a/apps/desktop/src/main/controllers/ShellCommandCtr.ts
+++ b/apps/desktop/src/main/controllers/ShellCommandCtr.ts
@@ -1,5 +1,8 @@
+import type { SandboxCapability } from '@lobechat/device-sandbox';
import type {
DesktopShellSettings,
+ DeviceSandboxCapabilityResult,
+ DeviceSandboxInstallResult,
GetCommandOutputParams,
GetCommandOutputResult,
KillCommandParams,
@@ -77,12 +80,132 @@ export default class ShellCommandCtr extends ControllerModule {
return settings;
}
+ /**
+ * Capability verdict, resolved at most once per app run and downgradable.
+ *
+ * Imported dynamically on purpose: a static import would pull
+ * `@anthropic-ai/sandbox-runtime` into every desktop launch. Nothing loads
+ * SRT until someone actually asks for a sandbox.
+ */
+ private sandboxCapability?: Promise<SandboxCapability>;
+
+ private probeSandbox(): Promise<SandboxCapability> {
+ return (this.sandboxCapability ??= (async () => {
+ try {
+ const { probeSandboxCapability } = await import('@lobechat/device-sandbox');
+ return await probeSandboxCapability();
+ } catch (error) {
+ // The probe itself can throw on an unsupported host instead of
+ // reporting unavailability. Any failure means "no sandbox here" โ€” the
+ // picker must never offer the option on the strength of a crashed
+ // probe.
+ logger.warn('Sandbox capability probe failed:', error);
+ return {
+ available: false,
+ backend: 'none' as const,
+ networkIsolation: false,
+ reason: (error as Error).message,
+ };
+ }
+ })());
+ }
+
+ /**
+ * Record that the sandbox could not actually be established, so the picker
+ * stops offering it.
+ *
+ * The cheap probe only checks that the backend is installed and its
+ * dependencies resolve; parts of the fence (on Windows, the egress filter and
+ * the secondary-logon spawn) are exercised only when the first real process
+ * starts. A host can therefore pass the probe and still fail every command โ€”
+ * observed on a Windows machine where `CreateProcessWithLogonW` is denied.
+ * Without this the user re-picks a permanently broken environment forever.
+ *
+ * Downgrade only, never an upgrade: a host that failed once stays failed for
+ * this app run. Recovering usually means installing something, which means
+ * restarting anyway.
+ */
+ private downgradeSandboxCapability(error: Error) {
+ logger.warn('Sandbox unavailable at launch, downgrading capability:', error);
+ this.sandboxCapability = Promise.resolve({
+ available: false,
+ backend: 'none' as const,
+ networkIsolation: false,
+ reason: error.message,
+ });
+ }
+
+ /**
+ * Whether this host can run sandboxed commands at all. The renderer asks
+ * before offering the "Local Sandbox" execution environment, so an
+ * unsupported host shows a disabled row carrying the real reason โ€” and, when
+ * the app can fix it, a button โ€” instead of an option that fails on first
+ * use.
+ */
+ @IpcMethod()
+ async getSandboxCapability(): Promise<DeviceSandboxCapabilityResult> {
+ const capability = await this.probeSandbox();
+ const { canInstallSandbox } = await import('@lobechat/device-sandbox');
+ return {
+ available: capability.available,
+ // Only worth advertising while something is actually missing.
+ canInstall: !capability.available && canInstallSandbox(),
+ reason: capability.reason,
+ };
+ }
+
+ /**
+ * Provision the sandbox backend on this machine, then re-read the capability.
+ *
+ * Users install the desktop app expecting its features to work; making them
+ * run a CLI first would be a broken promise. This is that setup, behind an
+ * explicit click โ€” it raises a UAC prompt and creates a dedicated Windows
+ * account, which must never happen implicitly.
+ *
+ * Always clears the cached verdict first: the whole point is to re-evaluate a
+ * host that previously said no, including one downgraded by a failed launch.
+ */
+ @IpcMethod()
+ async installSandbox(): Promise<DeviceSandboxInstallResult> {
+ const { installDeviceSandbox } = await import('@lobechat/device-sandbox');
+
+ let status: DeviceSandboxInstallResult['status'] = 'failed';
+ let error: string | undefined;
+ let instructions: string | undefined;
+
+ try {
+ const result = await installDeviceSandbox();
+ status = result.status;
+ instructions = result.instructions;
+ logger.info('Sandbox setup finished with status:', status);
+ } catch (caught) {
+ error = (caught as Error).message;
+ logger.error('Sandbox setup failed:', caught);
+ }
+
+ // Re-probe unconditionally. A cancelled or failed attempt can still have
+ // changed the host (the installer is idempotent and partially completes),
+ // and a stale "unavailable" would keep the option switched off after a
+ // setup that actually worked.
+ this.sandboxCapability = undefined;
+ const capability = await this.getSandboxCapability();
+
+ return { capability: { ...capability, instructions }, error, status };
+ }
+
@IpcMethod()
async handleRunCommand(params: RunCommandParams): Promise<RunCommandResult> {
const prefixMatch = SIMPLE_LH_PREFIX.exec(params.command);
if (prefixMatch) {
const cliCtr = this.app.getController(CliCtr);
if (cliCtr) {
+ // Deliberate carve-out: `lh` keeps its in-app route even for a
+ // sandboxed run. It is LobeHub's own control-plane CLI โ€” it needs the
+ // injected `LOBEHUB_JWT` and the server it talks to, both of which the
+ // sandbox strips (env allowlist) and blocks (no network). Sandboxing it
+ // would not harden anything the model can reach through it; it would
+ // just break agent self-management. The sandbox's promise is about
+ // model-authored shell commands, and this is not one.
const args = params.command.slice(prefixMatch[0].length).trim();
logger.debug('Routing lh command to CliCtr.runCliCommand:', args);
const result = await cliCtr.runCliCommand(args);
@@ -96,7 +219,56 @@ export default class ShellCommandCtr extends ControllerModule {
}
}
- return runCommand(params, { logger, processManager });
+ if (!params.sandbox) return runCommand(params, { logger, processManager });
+
+ // Sandboxed run. The policy is scoped to the run's working directory, so
+ // without one there is nothing to scope to โ€” refuse rather than fall back
+ // to `process.cwd()` (the app install directory on a packaged desktop),
+ // which would confine writes to a place the user never chose while still
+ // reporting success.
+ //
+ // `params.cwd` is trusted as the fence root because both callers strip the
+ // model's own `cwd` before dispatch and re-inject the run's configured
+ // working directory โ€” the server device-proxy unconditionally, and the
+ // 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) {
+ return {
+ error:
+ 'Local Sandbox requires a working directory. Set one for this agent (or topic) and run the command again.',
+ success: false,
+ };
+ }
+
+ // Check the host up front so an unsupported one gets a named, actionable
+ // failure. `createLocalSandboxPolicy` uses `onUnavailable: 'deny'`, so the
+ // command would fail anyway โ€” but the runner reports the raw backend reason
+ // ("Sandbox Runtime dependencies are unavailable: โ€ฆ"), which reads like a
+ // crash rather than "this environment isn't available on your machine".
+ const capability = await this.probeSandbox();
+ if (!capability.available) {
+ return {
+ error: `Local Sandbox is unavailable on this device: ${capability.reason ?? 'unsupported host'}. Switch the agent's execution environment to run this command.`,
+ success: false,
+ };
+ }
+
+ const { createLocalSandboxPolicy } = await import('@lobechat/device-sandbox');
+
+ // `runCommand` converts sandbox failures (policy conflict, busy runtime,
+ // a fence that cannot be established) into `{ success: false, error }`
+ // itself. It never falls back to an unsandboxed spawn, which is the
+ // guarantee the user opted into.
+ return runCommand(params, {
+ logger,
+ onSandboxUnavailable: (error) => this.downgradeSandboxCapability(error),
+ processManager,
+ sandboxPolicy: createLocalSandboxPolicy(params.cwd, {
+ allowNetwork: params.sandboxNetwork === true,
+ }),
+ });
}
@IpcMethod()
diff --git a/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
index 5f6fbf93f26..c8abb893d11 100644
--- a/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
@@ -36,6 +36,31 @@ vi.mock('../CliCtr', () => ({
default: class CliCtr {},
}));
+const {
+ mockCanInstallSandbox,
+ mockCreateSandboxLaunchPlan,
+ mockInstallDeviceSandbox,
+ mockProbeSandboxCapability,
+} = vi.hoisted(() => ({
+ mockCanInstallSandbox: vi.fn(),
+ mockCreateSandboxLaunchPlan: vi.fn(),
+ mockInstallDeviceSandbox: vi.fn(),
+ mockProbeSandboxCapability: vi.fn(),
+}));
+
+vi.mock('@lobechat/device-sandbox', () => ({
+ canInstallSandbox: () => mockCanInstallSandbox(),
+ installDeviceSandbox: () => mockInstallDeviceSandbox(),
+ createLocalSandboxPolicy: (cwd: string, options?: { allowNetwork?: boolean }) => ({
+ allowNetwork: options?.allowNetwork === true,
+ onUnavailable: 'deny',
+ writableRoots: [cwd],
+ ...(options?.allowNetwork ? { allowedNetworkDomains: ['*.npmjs.org'] } : {}),
+ }),
+ createSandboxLaunchPlan: (...args: unknown[]) => mockCreateSandboxLaunchPlan(...args),
+ probeSandboxCapability: () => mockProbeSandboxCapability(),
+}));
+
const mockCliCtr = {
runCliCommand: vi.fn().mockResolvedValue({ exitCode: 0, stderr: '', stdout: 'cli output\n' }),
};
@@ -180,6 +205,322 @@ describe('ShellCommandCtr (thin wrapper)', () => {
expect(result.success).toBe(true);
});
+ describe('local sandbox', () => {
+ beforeEach(() => {
+ // Default to a host with a one-click setup (Windows); the cases that care
+ // about the other platforms override it.
+ mockCanInstallSandbox.mockReturnValue(true);
+ mockProbeSandboxCapability.mockResolvedValue({
+ available: true,
+ backend: 'srt',
+ networkIsolation: true,
+ });
+ mockCreateSandboxLaunchPlan.mockResolvedValue({
+ args: ['-c', 'echo test'],
+ capability: { available: true, backend: 'srt', networkIsolation: true },
+ cmd: '/usr/bin/sandbox-exec',
+ env: {},
+ release: vi.fn(),
+ sandboxed: true,
+ });
+ });
+
+ it('never touches the sandbox for an ordinary command', async () => {
+ // The historical path must stay byte-identical for agents that never
+ // opted in โ€” including not loading the sandbox runtime at all.
+ mockProcessOutput = 'output\n';
+ setTimeout(() => {
+ mockChildProcess.exitCode = 0;
+ emitChildProcess('exit', 0);
+ emitChildProcess('close', 0);
+ }, 10);
+
+ await ctr.handleRunCommand({ command: 'echo test', cwd: '/repo' });
+
+ expect(mockProbeSandboxCapability).not.toHaveBeenCalled();
+ expect(mockCreateSandboxLaunchPlan).not.toHaveBeenCalled();
+ });
+
+ it('spawns the sandbox-wrapped command when the run is sandboxed', async () => {
+ mockProcessOutput = 'output\n';
+ setTimeout(() => {
+ mockChildProcess.exitCode = 0;
+ emitChildProcess('exit', 0);
+ emitChildProcess('close', 0);
+ }, 10);
+
+ await ctr.handleRunCommand({ command: 'echo test', cwd: '/repo', sandbox: true });
+
+ expect(mockCreateSandboxLaunchPlan).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cwd: '/repo',
+ policy: expect.objectContaining({ allowNetwork: false, writableRoots: ['/repo'] }),
+ }),
+ );
+ expect(mockSpawn).toHaveBeenCalledWith(
+ '/usr/bin/sandbox-exec',
+ ['-c', 'echo test'],
+ expect.anything(),
+ );
+ });
+
+ 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.
+ const result = await ctr.handleRunCommand({ command: 'echo test', sandbox: true });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('working directory');
+ expect(mockSpawn).not.toHaveBeenCalled();
+ });
+
+ it('fails the command instead of running it unsandboxed on an unsupported host', async () => {
+ mockProbeSandboxCapability.mockResolvedValue({
+ available: false,
+ backend: 'none',
+ networkIsolation: false,
+ reason: 'Sandbox Runtime does not support win32',
+ });
+
+ const result = await ctr.handleRunCommand({
+ command: 'echo test',
+ cwd: '/repo',
+ sandbox: true,
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('Sandbox Runtime does not support win32');
+ expect(mockSpawn).not.toHaveBeenCalled();
+ });
+
+ it('keeps the network shut unless the run opted in', async () => {
+ mockProcessOutput = 'output\n';
+ setTimeout(() => {
+ mockChildProcess.exitCode = 0;
+ emitChildProcess('exit', 0);
+ emitChildProcess('close', 0);
+ }, 10);
+
+ await ctr.handleRunCommand({ command: 'echo test', cwd: '/repo', sandbox: true });
+
+ expect(mockCreateSandboxLaunchPlan).toHaveBeenCalledWith(
+ expect.objectContaining({ policy: expect.objectContaining({ allowNetwork: false }) }),
+ );
+ });
+
+ it('opens the registry allowlist when the run opted in', async () => {
+ mockProcessOutput = 'output\n';
+ setTimeout(() => {
+ mockChildProcess.exitCode = 0;
+ emitChildProcess('exit', 0);
+ emitChildProcess('close', 0);
+ }, 10);
+
+ await ctr.handleRunCommand({
+ command: 'npm install',
+ cwd: '/repo',
+ sandbox: true,
+ sandboxNetwork: true,
+ });
+
+ expect(mockCreateSandboxLaunchPlan).toHaveBeenCalledWith(
+ expect.objectContaining({
+ policy: expect.objectContaining({
+ allowNetwork: true,
+ allowedNetworkDomains: ['*.npmjs.org'],
+ }),
+ }),
+ );
+ });
+
+ it('downgrades the advertised capability once a fence fails to establish', async () => {
+ // Observed on a real Windows host: dependencies check out, then the first
+ // spawn is denied. Without the downgrade the picker keeps offering an
+ // environment where every command fails.
+ mockCreateSandboxLaunchPlan.mockRejectedValue(
+ new Error('WFP egress fence could not be verified'),
+ );
+
+ expect(await ctr.getSandboxCapability()).toEqual({
+ available: true,
+ canInstall: false,
+ reason: undefined,
+ });
+
+ const result = await ctr.handleRunCommand({
+ command: 'echo test',
+ cwd: '/repo',
+ sandbox: true,
+ });
+
+ expect(result.success).toBe(false);
+ expect(mockSpawn).not.toHaveBeenCalled();
+ expect(await ctr.getSandboxCapability()).toEqual({
+ available: false,
+ canInstall: true,
+ reason: 'WFP egress fence could not be verified',
+ });
+ });
+
+ it('does not downgrade because a sandboxed command exited non-zero', async () => {
+ // Only a failure to BUILD the fence says anything about the host. A
+ // command failing inside a working sandbox is the command's problem.
+ mockProcessOutput = 'boom\n';
+ setTimeout(() => {
+ mockChildProcess.exitCode = 1;
+ emitChildProcess('exit', 1);
+ emitChildProcess('close', 1);
+ }, 10);
+
+ await ctr.handleRunCommand({ command: 'exit 1', cwd: '/repo', sandbox: true });
+
+ expect(await ctr.getSandboxCapability()).toEqual({
+ available: true,
+ canInstall: false,
+ reason: undefined,
+ });
+ });
+
+ it('reports the host verdict to the renderer', async () => {
+ mockProbeSandboxCapability.mockResolvedValue({
+ available: false,
+ backend: 'none',
+ networkIsolation: false,
+ reason: 'bubblewrap is not installed',
+ });
+
+ expect(await ctr.getSandboxCapability()).toEqual({
+ available: false,
+ canInstall: true,
+ reason: 'bubblewrap is not installed',
+ });
+ });
+
+ describe('setup', () => {
+ it('re-reads the capability after a successful install', async () => {
+ // Installing the desktop app is supposed to be enough: the row goes
+ // from unavailable to usable without the user touching a terminal.
+ mockCanInstallSandbox.mockReturnValue(true);
+ mockProbeSandboxCapability.mockResolvedValue({
+ available: false,
+ backend: 'none',
+ networkIsolation: false,
+ reason: 'Sandbox user is not provisioned',
+ });
+ expect(await ctr.getSandboxCapability()).toEqual({
+ available: false,
+ canInstall: true,
+ reason: 'Sandbox user is not provisioned',
+ });
+
+ mockInstallDeviceSandbox.mockResolvedValue({ status: 'installed' });
+ mockProbeSandboxCapability.mockResolvedValue({
+ available: true,
+ backend: 'srt',
+ networkIsolation: true,
+ });
+
+ const result = await ctr.installSandbox();
+
+ expect(result.status).toBe('installed');
+ expect(result.capability.available).toBe(true);
+ });
+
+ it('clears a downgraded verdict so a fixed host can recover', async () => {
+ // The downgrade is sticky for the app run; setup is the one thing that
+ // must be able to lift it, or the button could never work.
+ mockCanInstallSandbox.mockReturnValue(true);
+ mockCreateSandboxLaunchPlan.mockRejectedValue(new Error('egress fence unverified'));
+ await ctr.handleRunCommand({ command: 'echo test', cwd: '/repo', sandbox: true });
+ expect((await ctr.getSandboxCapability()).available).toBe(false);
+
+ mockInstallDeviceSandbox.mockResolvedValue({ status: 'installed' });
+ mockProbeSandboxCapability.mockResolvedValue({
+ available: true,
+ backend: 'srt',
+ networkIsolation: true,
+ });
+
+ expect((await ctr.installSandbox()).capability.available).toBe(true);
+ });
+
+ it('reports a dismissed elevation prompt as cancelled, not a failure', async () => {
+ mockCanInstallSandbox.mockReturnValue(true);
+ mockInstallDeviceSandbox.mockResolvedValue({ status: 'cancelled' });
+ mockProbeSandboxCapability.mockResolvedValue({
+ available: false,
+ backend: 'none',
+ networkIsolation: false,
+ reason: 'Sandbox user is not provisioned',
+ });
+
+ const result = await ctr.installSandbox();
+
+ expect(result.status).toBe('cancelled');
+ expect(result.error).toBeUndefined();
+ expect(result.capability.available).toBe(false);
+ });
+
+ it('surfaces an install failure without leaving the capability stale', async () => {
+ mockCanInstallSandbox.mockReturnValue(true);
+ mockInstallDeviceSandbox.mockRejectedValue(new Error('WFP filter install failed'));
+ mockProbeSandboxCapability.mockResolvedValue({
+ available: false,
+ backend: 'none',
+ networkIsolation: false,
+ reason: 'Sandbox user is not provisioned',
+ });
+
+ const result = await ctr.installSandbox();
+
+ expect(result.status).toBe('failed');
+ expect(result.error).toBe('WFP filter install failed');
+ expect(result.capability.available).toBe(false);
+ });
+
+ it('carries manual instructions when the app cannot install it', async () => {
+ mockCanInstallSandbox.mockReturnValue(false);
+ mockInstallDeviceSandbox.mockResolvedValue({
+ instructions: 'sudo apt install bubblewrap',
+ status: 'not-installable',
+ });
+ mockProbeSandboxCapability.mockResolvedValue({
+ available: false,
+ backend: 'none',
+ networkIsolation: false,
+ reason: 'bubblewrap is not installed',
+ });
+
+ const result = await ctr.installSandbox();
+
+ expect(result.status).toBe('not-installable');
+ expect(result.capability.canInstall).toBe(false);
+ expect(result.capability.instructions).toBe('sudo apt install bubblewrap');
+ });
+
+ it('does not offer setup on a host that already has a sandbox', async () => {
+ mockCanInstallSandbox.mockReturnValue(true);
+ mockProbeSandboxCapability.mockResolvedValue({
+ available: true,
+ backend: 'srt',
+ networkIsolation: true,
+ });
+
+ expect((await ctr.getSandboxCapability()).canInstall).toBe(false);
+ });
+ });
+
+ it('treats a crashing probe as no sandbox', async () => {
+ mockProbeSandboxCapability.mockRejectedValue(new Error('module not found'));
+
+ expect(await ctr.getSandboxCapability()).toEqual({
+ available: false,
+ canInstall: true,
+ reason: 'module not found',
+ });
+ });
+ });
+
it('should return error for non-existent shell_id', async () => {
const result = await ctr.handleGetCommandOutput({
shell_id: 'non-existent',
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
index ad93ef9b030..86c3f652dae 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
@@ -16,7 +16,7 @@ import {
import type { ChatToolPayload } from '@lobechat/types';
import { AgentModel } from '@/database/models/agent';
-import { isDeviceCapablePlan } from '@/helpers/executionTarget';
+import { isDeviceCapablePlan, isLocalSandboxEnabled } from '@/helpers/executionTarget';
import type { DeviceAccessReason } from '@/server/services/aiAgent/deviceToolAudit';
import {
isDeviceToolIdentifier,
@@ -211,6 +211,18 @@ export class ServerToolTransport implements ToolTransport {
executionTimeoutMs: timeoutMs,
groupId: context.state.metadata?.groupId,
isSubAgent: context.state.metadata?.isSubAgent === true,
+ // Sandboxing qualifies a `local` run, so it is gated on the plan's
+ // resolved target rather than the stored flag: a config that says
+ // `localSandbox` but landed on `sandbox`/`device` was never fenced,
+ // and telling the device otherwise would fence the wrong run.
+ localSandbox: context.state.metadata?.executionPlan
+ ? isLocalSandboxEnabled(
+ context.state.metadata?.agentConfig?.agencyConfig,
+ context.state.metadata.executionPlan.target,
+ )
+ : undefined,
+ localSandboxNetwork:
+ context.state.metadata?.agentConfig?.agencyConfig?.localSandboxNetwork === true,
memoryToolPermission:
context.state.metadata?.agentConfig?.chatConfig?.memory?.toolPermission,
messageId: context.state.metadata?.sourceMessageId,
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 70f785fa2af..949e67a4806 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
@@ -225,6 +225,104 @@ describe('localSystemRuntime', () => {
expect(parseArgs()).toEqual({ command: 'git status', cwd: '/Users/me/repo' });
});
+ it('forwards the sandbox decision to runCommand', async () => {
+ 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: 'git status' });
+
+ expect(parseArgs()).toEqual({
+ command: 'git status',
+ cwd: '/Users/me/repo',
+ sandbox: true,
+ sandboxNetwork: false,
+ });
+ });
+
+ it('never lets a model-supplied cwd become the fence root', async () => {
+ // The sandbox policy is built from `params.cwd` on the device, so this
+ // stripping is what stops a guessed or replayed `cwd` from choosing what
+ // the command is fenced to. `cwd` is off-manifest for every api, but the
+ // arg schema does not reject extra properties โ€” pin the behaviour here so
+ // relaxing the strip can never silently hand the model its own fence.
+ 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: 'cat ~/.ssh/id_rsa',
+ cwd: '/Users/me',
+ });
+
+ expect(parseArgs().cwd).toBe('/Users/me/repo');
+ expect(parseArgs().sandbox).toBe(true);
+ });
+
+ it('forwards the network allowance for a fenced run', async () => {
+ mockExecuteToolCall.mockResolvedValue({ content: '', success: true });
+ const proxy = localSystemRuntime.factory({
+ activeDeviceId: 'device-1',
+ localSandbox: true,
+ localSandboxNetwork: true,
+ toolManifestMap: {},
+ userId: 'user-1',
+ workingDirectory: '/Users/me/repo',
+ });
+ await proxy[LocalSystemApiName.runCommand]({ command: 'npm install' });
+
+ expect(parseArgs().sandboxNetwork).toBe(true);
+ });
+
+ it('omits the network flag when the run is not fenced', async () => {
+ // `sandboxNetwork` is meaningless without a sandbox โ€” don't add noise to
+ // an unfenced command's args.
+ mockExecuteToolCall.mockResolvedValue({ content: '', success: true });
+ const proxy = localSystemRuntime.factory({
+ activeDeviceId: 'device-1',
+ localSandbox: false,
+ localSandboxNetwork: true,
+ toolManifestMap: {},
+ userId: 'user-1',
+ workingDirectory: '/Users/me/repo',
+ });
+ await proxy[LocalSystemApiName.runCommand]({ command: 'git status' });
+
+ expect(parseArgs()).not.toHaveProperty('sandboxNetwork');
+ expect(parseArgs().sandbox).toBe(false);
+ });
+
+ it('overrides a sandbox flag the model tried to set itself', async () => {
+ // The manifest never exposes `sandbox`, but a model that guesses the field
+ // must not be able to unfence its own commands โ€” the run's context wins.
+ 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: 'rm -rf /', sandbox: false });
+
+ expect(parseArgs().sandbox).toBe(true);
+ });
+
+ it('leaves runCommand untouched when the run is not sandboxed', async () => {
+ const proxy = buildProxy('/Users/me/repo');
+ await proxy[LocalSystemApiName.runCommand]({ command: 'git status' });
+
+ expect(parseArgs()).not.toHaveProperty('sandbox');
+ });
+
it('injects scope into search ops that honor it', async () => {
const proxy = buildProxy('/Users/me/repo');
await proxy[LocalSystemApiName.grepContent]({ pattern: 'TODO' });
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
index dc6c894e193..942b3b957dc 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
@@ -114,6 +114,23 @@ export const localSystemRuntime: ServerRuntimeRegistration = {
if (api.name === LocalSystemApiName.runCommand && typeof finalArgs?.command === 'string') {
const lhEnv = buildDeviceLhEnv(await getContentWorkspaceId());
if (lhEnv) finalArgs = { ...finalArgs, env: { ...lhEnv, ...finalArgs.env } };
+
+ // The sandbox decision belongs to the run's owner, not to the model:
+ // it is set here from the resolved execution context, overriding
+ // anything that arrived in the LLM args (the manifest doesn't expose
+ // the field, but a model that guessed it must not be able to switch
+ // its own fence off โ€” or on).
+ if (context.localSandbox !== undefined) {
+ finalArgs = {
+ ...finalArgs,
+ sandbox: context.localSandbox,
+ // Only meaningful for a fenced run, so don't add noise to the
+ // args of an unfenced one.
+ ...(context.localSandbox
+ ? { sandboxNetwork: context.localSandboxNetwork === true }
+ : {}),
+ };
+ }
}
return deviceGateway.executeToolCall(
diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.ts
index f2ce99f8255..8a907b9a49f 100644
--- a/apps/server/src/services/toolExecution/types.ts
+++ b/apps/server/src/services/toolExecution/types.ts
@@ -219,6 +219,22 @@ export interface ToolExecutionContext {
groupId?: string | null;
/** Whether this tool call is executing inside an isolated sub-agent run. */
isSubAgent?: boolean;
+ /**
+ * The run resolved to a local device AND the owner asked for the device
+ * sandbox (`agencyConfig.localSandbox`). The Local System device-proxy passes
+ * it to `runCommand` so the desktop confines the spawned command.
+ *
+ * Resolved once against the run's effective execution target โ€” never
+ * re-derived downstream from the raw flag, which says nothing about where the
+ * run actually landed.
+ */
+ localSandbox?: boolean;
+ /**
+ * The sandboxed run may reach the package-registry allowlist
+ * (`agencyConfig.localSandboxNetwork`). Meaningless without
+ * {@link localSandbox}.
+ */
+ localSandboxNetwork?: boolean;
/**
* Optional server-owned embedding runtime for memory search.
*
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 0d1ba227a0e..e4ba1568b8f 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -630,6 +630,12 @@
"heteroAgent.executionTarget.loading": "Loading devicesโ€ฆ",
"heteroAgent.executionTarget.local": "Local device",
"heteroAgent.executionTarget.localDesc": "Run as a local process on this desktop app",
+ "heteroAgent.executionTarget.localSandbox": "Local sandbox",
+ "heteroAgent.executionTarget.localSandboxDesc": "Run on this computer, with commands limited to the working directory and no network",
+ "heteroAgent.executionTarget.localSandboxDescNetwork": "Run on this computer, with commands limited to the working directory and to common developer domains",
+ "heteroAgent.executionTarget.localSandboxNetworkTip": "Let sandboxed commands reach package registries and source forges โ€” npm, PyPI, crates.io, RubyGems, Go, GitHub, GitLab. Every other domain stays blocked; the sandbox cannot open the network entirely.",
+ "heteroAgent.executionTarget.localSandboxSetUp": "Set up",
+ "heteroAgent.executionTarget.localSandboxUnavailable": "Not available on this device: {{reason}}",
"heteroAgent.executionTarget.manage": "Manage",
"heteroAgent.executionTarget.noDevices": "No remote devices yet. Run `lh connect` on another machine to add one.",
"heteroAgent.executionTarget.noWorkspaceDevices": "No workspace devices yet. Run `{{cmd}}` on a machine to enroll it for every member.",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 0cbbf0118e3..a7fc7855f93 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -630,6 +630,12 @@
"heteroAgent.executionTarget.loading": "ๆญฃๅœจๅŠ ่ฝฝ่ฎพๅค‡โ€ฆ",
"heteroAgent.executionTarget.local": "ๆœฌๅœฐ่ฎพๅค‡",
"heteroAgent.executionTarget.localDesc": "ๅœจๅฝ“ๅ‰ๆกŒ้ข็ซฏไปฅๆœฌๅœฐ่ฟ›็จ‹่ฟ่กŒ",
+ "heteroAgent.executionTarget.localSandbox": "ๆœฌๆœบๆฒ™็ฎฑ",
+ "heteroAgent.executionTarget.localSandboxDesc": "ๅœจๆœฌๆœบ่ฟ่กŒ๏ผŒๅ‘ฝไปคไป…่ƒฝๆ”นๅŠจๅทฅไฝœ็›ฎๅฝ•ไธ”ๆ— ๆณ•่”็ฝ‘",
+ "heteroAgent.executionTarget.localSandboxDescNetwork": "ๅœจๆœฌๆœบ่ฟ่กŒ๏ผŒๅ‘ฝไปคไป…่ƒฝๆ”นๅŠจๅทฅไฝœ็›ฎๅฝ•๏ผŒไธ”ไป…ๅฏ่ฎฟ้—ฎๅธธ็”จๅผ€ๅ‘ๅŸŸๅ",
+ "heteroAgent.executionTarget.localSandboxNetworkTip": "ๅ…่ฎธๆฒ™็ฎฑๅ†…็š„ๅ‘ฝไปค่ฎฟ้—ฎๅŒ…็ฎก็†ๅ™จไธŽไปฃ็ ๆ‰˜็ฎกๅŸŸๅ๏ผšnpmใ€PyPIใ€crates.ioใ€RubyGemsใ€Goใ€GitHubใ€GitLabใ€‚ๅ…ถไฝ™ๅŸŸๅไปไผš่ขซๆ‹ฆๆˆชโ€”โ€”ๆฒ™็ฎฑๆ— ๆณ•ๅฎŒๅ…จๆ”พๅผ€็ฝ‘็ปœใ€‚",
+ "heteroAgent.executionTarget.localSandboxSetUp": "ๅฏ็”จ",
+ "heteroAgent.executionTarget.localSandboxUnavailable": "ๆญค่ฎพๅค‡ไธŠไธๅฏ็”จ๏ผš{{reason}}",
"heteroAgent.executionTarget.manage": "็ฎก็†",
"heteroAgent.executionTarget.noDevices": "ๆš‚ๆ— ่ฟœ็จ‹่ฎพๅค‡ใ€‚ๅœจๅฆไธ€ๅฐๆœบๅ™จไธŠๆ‰ง่กŒ `lh connect` ๅณๅฏๆŽฅๅ…ฅใ€‚",
"heteroAgent.executionTarget.noWorkspaceDevices": "ๆš‚ๆ— ๅทฅไฝœๅŒบ่ฎพๅค‡ใ€‚ๅœจไธ€ๅฐๆœบๅ™จไธŠๆ‰ง่กŒ `{{cmd}}` ๅณๅฏๆณจๅ†Œ,ไพ›ๆ‰€ๆœ‰ๆˆๅ‘˜ไฝฟ็”จใ€‚",
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 36e03fe3025..bfdec1fac0b 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
@@ -2,14 +2,16 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { localSystemExecutor } from './index';
-const { globFilesMock, searchFilesMock } = vi.hoisted(() => ({
+const { globFilesMock, runCommandMock, searchFilesMock } = vi.hoisted(() => ({
globFilesMock: vi.fn(),
+ runCommandMock: vi.fn(),
searchFilesMock: vi.fn(),
}));
vi.mock('@/services/electron/localFileService', () => ({
localFileService: {
globFiles: globFilesMock,
+ runCommand: runCommandMock,
searchLocalFiles: searchFilesMock,
},
}));
@@ -224,3 +226,66 @@ describe('LocalSystemExecutor', () => {
});
});
});
+
+describe('LocalSystemExecutor.runCommand', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ runCommandMock.mockResolvedValue({ content: '', success: true });
+ });
+
+ it('fences the command and anchors it to the run cwd when the context says so', async () => {
+ await localSystemExecutor.runCommand(
+ { command: 'git status' },
+ { localSandbox: true, messageId: 'm-1', workingDirectory: '/repo' },
+ );
+
+ expect(runCommandMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ command: 'git status',
+ cwd: '/repo',
+ sandbox: true,
+ sandboxNetwork: false,
+ }),
+ );
+ });
+
+ it('forwards the network allowance for a fenced run', async () => {
+ await localSystemExecutor.runCommand(
+ { command: 'npm install' },
+ {
+ localSandbox: true,
+ localSandboxNetwork: true,
+ messageId: 'm-1',
+ workingDirectory: '/repo',
+ },
+ );
+
+ expect(runCommandMock).toHaveBeenCalledWith(
+ expect.objectContaining({ sandbox: true, sandboxNetwork: true }),
+ );
+ });
+
+ it('leaves an unfenced command without either sandbox field', async () => {
+ // The historical path must not shift for agents that never opted in.
+ await localSystemExecutor.runCommand(
+ { command: 'git status' },
+ { messageId: 'm-1', workingDirectory: '/repo' },
+ );
+
+ const args = runCommandMock.mock.calls[0][0];
+ expect(args).not.toHaveProperty('sandbox');
+ expect(args).not.toHaveProperty('sandboxNetwork');
+ });
+
+ 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
+ // field cannot widen its own fence to an arbitrary directory.
+ await localSystemExecutor.runCommand(
+ { command: 'git status', cwd: '/etc' },
+ { localSandbox: true, messageId: 'm-1', workingDirectory: '/repo' },
+ );
+
+ expect(runCommandMock).toHaveBeenCalledWith(expect.objectContaining({ cwd: '/repo' }));
+ });
+});
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 df2f5abf876..2b4526c8a85 100644
--- a/packages/builtin-tool-local-system/src/client/executor/index.ts
+++ b/packages/builtin-tool-local-system/src/client/executor/index.ts
@@ -134,8 +134,20 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {
// ==================== Shell Commands ====================
+ // The sandbox decision rides on the context, resolved by the caller from the
+ // agent's config โ€” never from the model's args, which the manifest doesn't
+ // 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('runCommand', params, ctx);
+ this.execute(
+ 'runCommand',
+ ctx?.localSandbox === true
+ ? { ...params, sandbox: true, sandboxNetwork: ctx?.localSandboxNetwork === true }
+ : params,
+ ctx,
+ );
getCommandOutput = (params: GetCommandOutputParams, ctx?: BuiltinToolContext) =>
this.execute('getCommandOutput', params, ctx);
diff --git a/packages/device-sandbox/src/__tests__/presets.test.ts b/packages/device-sandbox/src/__tests__/presets.test.ts
new file mode 100644
index 00000000000..ac7e3dde717
--- /dev/null
+++ b/packages/device-sandbox/src/__tests__/presets.test.ts
@@ -0,0 +1,62 @@
+import os from 'node:os';
+
+import { describe, expect, it } from 'vitest';
+
+import { normalizeSandboxPolicy } from '../policy';
+import { createLocalSandboxPolicy, LOCAL_SANDBOX_NETWORK_DOMAINS } from '../presets';
+
+describe('createLocalSandboxPolicy', () => {
+ it('confines writes to the working directory and the temp dir', () => {
+ const policy = createLocalSandboxPolicy(process.cwd());
+
+ expect(policy.writableRoots).toEqual([process.cwd(), os.tmpdir()]);
+ });
+
+ it('denies network with no allowlist by default', () => {
+ // `normalizeSandboxPolicy` throws when `allowNetwork` is set without a
+ // non-empty domain allowlist, so a policy that accidentally opened the
+ // network would fail here rather than at the user's machine.
+ const policy = createLocalSandboxPolicy(process.cwd());
+
+ expect(policy.allowNetwork).toBe(false);
+ expect(policy.allowedNetworkDomains).toBeUndefined();
+ expect(() => normalizeSandboxPolicy(policy)).not.toThrow();
+ });
+
+ it('opens only the registry allowlist when network is allowed', () => {
+ const policy = createLocalSandboxPolicy(process.cwd(), { allowNetwork: true });
+
+ expect(policy.allowNetwork).toBe(true);
+ expect(policy.allowedNetworkDomains).toEqual([...LOCAL_SANDBOX_NETWORK_DOMAINS]);
+ expect(() => normalizeSandboxPolicy(policy)).not.toThrow();
+ });
+
+ it('keeps every allowlist entry within what the backend accepts', () => {
+ // The sandbox backend rejects a bare `*` and overly broad patterns like
+ // `*.com` outright, so a careless addition here would make every network
+ // -enabled run fail at config validation instead of at review.
+ for (const domain of LOCAL_SANDBOX_NETWORK_DOMAINS) {
+ expect(domain).not.toBe('*');
+ expect(domain).toContain('.');
+ expect(domain.startsWith('*.') ? domain.slice(2) : domain).toContain('.');
+ // no wildcard anywhere except a leading `*.`
+ expect(domain.replace(/^\*\./, '')).not.toContain('*');
+ }
+ });
+
+ it('fails closed when no sandbox backend is available', () => {
+ // The whole point of the option: an unavailable backend must abort the
+ // command, never downgrade it to an unsandboxed spawn.
+ expect(createLocalSandboxPolicy(process.cwd()).onUnavailable).toBe('deny');
+ });
+
+ it('leaves reads unrestricted', () => {
+ // Commands legitimately read toolchains outside the project (node, rustup,
+ // Homebrew). The promise is "can't modify anything outside the working
+ // directory", not "can't see anything".
+ const policy = createLocalSandboxPolicy(process.cwd());
+
+ expect(policy.deniedReadRoots).toBeUndefined();
+ expect(policy.readableRoots).toBeUndefined();
+ });
+});
diff --git a/packages/device-sandbox/src/__tests__/runtime.test.ts b/packages/device-sandbox/src/__tests__/runtime.test.ts
new file mode 100644
index 00000000000..f5844bda9eb
--- /dev/null
+++ b/packages/device-sandbox/src/__tests__/runtime.test.ts
@@ -0,0 +1,101 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { SrtSandboxRuntime } from '../runtime';
+import type { SandboxCapability, SandboxPolicy } from '../types';
+
+const { mockCleanup, mockGetConfig, mockInitialize, mockIsEnabled, mockReset, mockWrap } =
+ vi.hoisted(() => ({
+ mockCleanup: vi.fn(),
+ mockGetConfig: vi.fn(),
+ mockInitialize: vi.fn(),
+ mockIsEnabled: vi.fn(),
+ mockReset: vi.fn(),
+ mockWrap: vi.fn(),
+ }));
+
+vi.mock('@anthropic-ai/sandbox-runtime', () => ({
+ SandboxManager: {
+ cleanupAfterCommand: mockCleanup,
+ getConfig: mockGetConfig,
+ initialize: mockInitialize,
+ isSandboxingEnabled: mockIsEnabled,
+ reset: mockReset,
+ wrapWithSandboxArgv: mockWrap,
+ },
+ getSrtWinPath: () => 'C:\\packaged\\srt-win.exe',
+}));
+
+const capability: SandboxCapability = {
+ available: true,
+ backend: 'srt',
+ networkIsolation: true,
+};
+
+const policyFor = (root: string): SandboxPolicy => ({
+ allowNetwork: false,
+ onUnavailable: 'deny',
+ writableRoots: [root],
+});
+
+// The runtime hashes the config the backend receives, so a stable stand-in for
+// `createSrtConfig` keeps these tests about policy switching rather than config
+// shape. Roots are passed through unnormalized on purpose โ€” `normalizeSandboxPolicy`
+// requires the paths to exist on disk, which is not what is under test here.
+vi.mock('../srt', () => ({
+ createSrtConfig: (policy: SandboxPolicy) => ({ roots: policy.writableRoots }),
+}));
+
+describe('SrtSandboxRuntime policy switching', () => {
+ let runtime: SrtSandboxRuntime;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ runtime = new SrtSandboxRuntime();
+ mockInitialize.mockResolvedValue(undefined);
+ mockIsEnabled.mockReturnValue(true);
+ mockReset.mockResolvedValue(undefined);
+ mockWrap.mockResolvedValue({ argv: ['wrapper', '-c', 'cmd'], env: {} });
+ mockGetConfig.mockImplementation(() => mockInitialize.mock.lastCall?.[0]);
+ });
+
+ const launch = (root: string) =>
+ runtime.createLaunchPlan(
+ { command: { args: ['-c', 'echo hi'], cmd: '/bin/sh' }, cwd: root, policy: policyFor(root) },
+ capability,
+ );
+
+ it('reuses the session when the policy is unchanged', async () => {
+ const first = await launch('/project-a');
+ first.release?.();
+ const second = await launch('/project-a');
+ second.release?.();
+
+ expect(mockInitialize).toHaveBeenCalledTimes(1);
+ expect(mockReset).not.toHaveBeenCalled();
+ });
+
+ it('re-initializes when the policy changes and nothing is running', async () => {
+ // Switching agents, opening another project, or flipping the network
+ // toggle all change the policy. Refusing them would make the sandbox
+ // usable exactly once per app launch.
+ const first = await launch('/project-a');
+ first.release?.();
+
+ const second = await launch('/project-b');
+ second.release?.();
+
+ expect(mockReset).toHaveBeenCalledTimes(1);
+ expect(mockInitialize).toHaveBeenCalledTimes(2);
+ expect(mockInitialize.mock.calls[1][0]).toEqual({ roots: ['/project-b'] });
+ });
+
+ it('refuses to swap the policy out from under a running command', async () => {
+ // The fence a live command is running inside must not be replaced.
+ await launch('/project-a'); // deliberately not released
+
+ await expect(launch('/project-b')).rejects.toMatchObject({
+ code: 'SANDBOX_POLICY_CONFLICT',
+ });
+ expect(mockReset).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/device-sandbox/src/index.ts b/packages/device-sandbox/src/index.ts
index b1f5b9f3660..a9ab35ed38c 100644
--- a/packages/device-sandbox/src/index.ts
+++ b/packages/device-sandbox/src/index.ts
@@ -2,8 +2,15 @@ export { probeSandboxCapability } from './capability';
export { createSandboxEnv } from './env';
export { createSandboxLaunchPlan } from './launchPlan';
export { normalizeSandboxPolicy, normalizeWritableRoots } from './policy';
+export {
+ createLocalSandboxPolicy,
+ LOCAL_SANDBOX_NETWORK_DOMAINS,
+ type LocalSandboxPolicyOptions,
+} from './presets';
export { SrtSandboxRuntime, srtSandboxRuntime } from './runtime';
+export { canInstallSandbox, installDeviceSandbox } from './setup';
export { createSrtConfig } from './srt';
+export { ensureStagedSrtWin, resolveSrtWinSource } from './srtWinStaging';
export type {
CreateSandboxLaunchPlanOptions,
SandboxBackend,
@@ -13,6 +20,8 @@ export type {
SandboxErrorCode,
SandboxLaunchPlan,
SandboxPolicy,
+ SandboxSetupResult,
+ SandboxSetupStatus,
SandboxUnavailableBehavior,
} from './types';
export { SandboxError } from './types';
diff --git a/packages/device-sandbox/src/presets.ts b/packages/device-sandbox/src/presets.ts
new file mode 100644
index 00000000000..e68c45e01be
--- /dev/null
+++ b/packages/device-sandbox/src/presets.ts
@@ -0,0 +1,90 @@
+import os from 'node:os';
+
+import type { SandboxPolicy } from './types';
+
+/**
+ * Domains reachable when a Local Sandbox run opts into network access.
+ *
+ * There is no "allow everything" to offer: SRT's schema rejects a bare `*` and
+ * overly broad patterns like `*.com` outright, so network access is always
+ * *some* allowlist. This is the smallest set that makes the common reason for
+ * wanting the network at all โ€” installing dependencies and talking to the
+ * project's own forge โ€” work.
+ *
+ * Wildcards match strict subdomains only, so an apex domain that is itself
+ * contacted (`github.com`, `pypi.org`) is listed alongside its `*.` form.
+ *
+ * Deliberately excluded: model/API providers and anything that could carry data
+ * out on the model's behalf. The point of the sandbox is that a command cannot
+ * exfiltrate what it reads; a general-purpose egress hole would give that back.
+ */
+export const LOCAL_SANDBOX_NETWORK_DOMAINS = [
+ // npm / yarn / pnpm
+ '*.npmjs.org',
+ '*.npmmirror.com',
+ '*.yarnpkg.com',
+ 'npmjs.org',
+ 'registry.npmmirror.com',
+ // Python
+ '*.pypi.org',
+ '*.pythonhosted.org',
+ 'pypi.org',
+ // Rust
+ '*.crates.io',
+ 'crates.io',
+ // Go
+ 'proxy.golang.org',
+ 'sum.golang.org',
+ // Ruby
+ '*.rubygems.org',
+ 'rubygems.org',
+ // source forges
+ '*.github.com',
+ '*.githubusercontent.com',
+ '*.gitlab.com',
+ 'github.com',
+ 'gitlab.com',
+] as const;
+
+export interface LocalSandboxPolicyOptions {
+ /**
+ * Allow the run to reach {@link LOCAL_SANDBOX_NETWORK_DOMAINS}. Everything
+ * else stays blocked โ€” this is never "the network is open".
+ */
+ allowNetwork?: boolean;
+}
+
+/**
+ * Policy for the desktop "Local Sandbox" execution environment โ€” the option a
+ * user picks in the execution-environment switcher to keep an agent's shell
+ * commands inside the run's working directory.
+ *
+ * Deliberately narrow, because the picker promises exactly this and nothing
+ * more:
+ *
+ * - **writes** are confined to the run's `cwd` plus the OS temp directory.
+ * Tooling that cannot write a temp file at all (compilers, package managers,
+ * `git`) fails in ways that read as product bugs, so temp is part of the
+ * contract rather than a leak the user has to discover.
+ * - **reads** stay unrestricted. SRT's read denial is a separate axis
+ * (`deniedReadRoots`), and a blanket read jail would break every command that
+ * touches a toolchain outside the project (node_modules symlinks, rustup,
+ * Homebrew). "Can't modify anything outside the project" is the honest,
+ * enforceable promise; "can't see anything" is not.
+ * - **network is denied by default**, and even when allowed it is only the
+ * package-registry allowlist above.
+ *
+ * `onUnavailable: 'deny'` is the whole point of the option: if SRT can't be
+ * initialized on this host, the command must fail loudly. Silently running
+ * unsandboxed would hand the user a security guarantee the process never
+ * applied.
+ */
+export const createLocalSandboxPolicy = (
+ cwd: string,
+ { allowNetwork = false }: LocalSandboxPolicyOptions = {},
+): SandboxPolicy => ({
+ allowNetwork,
+ onUnavailable: 'deny',
+ writableRoots: [cwd, os.tmpdir()],
+ ...(allowNetwork ? { allowedNetworkDomains: [...LOCAL_SANDBOX_NETWORK_DOMAINS] } : {}),
+});
diff --git a/packages/device-sandbox/src/runtime.ts b/packages/device-sandbox/src/runtime.ts
index 6be8445dfe1..04f8616a403 100644
--- a/packages/device-sandbox/src/runtime.ts
+++ b/packages/device-sandbox/src/runtime.ts
@@ -24,13 +24,25 @@ export class SrtSandboxRuntime {
if (this.initialization) await this.initialization;
if (this.initializedFingerprint) {
- if (this.initializedFingerprint !== requestedFingerprint) {
+ if (this.initializedFingerprint === requestedFingerprint) return;
+
+ // The backend holds ONE policy per process, and the working directory is
+ // part of it โ€” so switching agents, opening a second project, or flipping
+ // the network toggle all arrive here. Refusing them would make the
+ // sandbox usable exactly once per app launch.
+ //
+ // Re-initializing is safe only while nothing is running under the old
+ // policy: a live command's fence must never be swapped out from under it.
+ // `shutdown` enforces that and throws SANDBOX_BUSY otherwise, which is the
+ // honest answer โ€” the caller retries once the other command finishes.
+ if (this.activeCommands > 0) {
throw new SandboxError(
'SANDBOX_POLICY_CONFLICT',
- 'Sandbox Runtime is already initialized with a different device policy',
+ `Sandbox Runtime is busy with ${this.activeCommands} command(s) under a different device policy`,
);
}
- return;
+
+ await this.shutdown();
}
this.initialization = SandboxManager.initialize(config, undefined, true);
@@ -56,9 +68,24 @@ export class SrtSandboxRuntime {
const config = createSrtConfig(options.policy);
await this.ensureInitialized(config);
+ // The shell the sandboxed child runs under has to be one that exists on
+ // this OS. `/bin/sh` was hardcoded here, which is why every Windows launch
+ // died with `CreateProcessAsUserW(/bin/sh): path not found` even after the
+ // fence itself came up cleanly.
+ //
+ // The caller already resolved the right shell for the platform
+ // (`getShellConfig` โ†’ Git Bash / PowerShell / cmd, with the command as the
+ // final argv entry), so reuse it rather than guessing again: the sandboxed
+ // spawn then matches the unsandboxed one exactly, flags included.
+ const { args, cmd } = options.command;
+ const [command, binShell] =
+ process.platform === 'win32'
+ ? [args.at(-1) ?? '', { args: args.slice(0, -1), exe: cmd }]
+ : [serializeCommand(options.command), '/bin/sh'];
+
const wrapped = await SandboxManager.wrapWithSandboxArgv(
- serializeCommand(options.command),
- '/bin/sh',
+ command,
+ binShell,
undefined,
undefined,
options.cwd ?? process.cwd(),
diff --git a/packages/device-sandbox/src/setup.ts b/packages/device-sandbox/src/setup.ts
new file mode 100644
index 00000000000..34072c16464
--- /dev/null
+++ b/packages/device-sandbox/src/setup.ts
@@ -0,0 +1,64 @@
+import type { SandboxSetupResult } from './types';
+
+/**
+ * Whether this platform has a one-click setup the app can run for the user.
+ *
+ * Only Windows does: its backend needs a dedicated `srt-sandbox` account and a
+ * WFP filter set, which `srt-win install` provisions in a single self-elevating
+ * step. macOS needs nothing (Seatbelt ships with the OS), and Linux needs a
+ * distro package (`bubblewrap`) that only the system's own package manager may
+ * install โ€” offering a button that can't deliver would be worse than telling
+ * the user what to run.
+ */
+export const canInstallSandbox = (platform: NodeJS.Platform = process.platform): boolean =>
+ platform === 'win32';
+
+/**
+ * Provision whatever the sandbox backend needs on this machine.
+ *
+ * Users should not have to prepare anything before the desktop app can fence a
+ * command โ€” installing the app is supposed to be enough. This is the "enough"
+ * part: a user-initiated setup the app runs on their behalf.
+ *
+ * On Windows this raises exactly one UAC prompt (the helper self-elevates) and
+ * is idempotent, so re-running after a partial or failed attempt is safe.
+ * Dismissing that prompt is a choice, not a failure: it comes back as
+ * `cancelled` so the caller can leave the UI exactly as it was.
+ *
+ * Never called implicitly โ€” creating a Windows account and installing network
+ * filters is not something to do behind a user's back, so it hangs off an
+ * explicit button.
+ */
+export const installDeviceSandbox = async (): Promise<SandboxSetupResult> => {
+ if (!canInstallSandbox()) {
+ const { windowsInstallInstructions } = await import('@anthropic-ai/sandbox-runtime');
+ return {
+ // Linux's dependency is a distro package; macOS should never get here at
+ // all (an unavailable Seatbelt means something else is wrong, and the
+ // probe's own reason says more than a generic instruction would).
+ instructions:
+ process.platform === 'linux'
+ ? // Both are hard requirements: the backend errors out without
+ // bubblewrap, and separately without ripgrep, which it uses to
+ // expand deny-path globs for bwrap. Naming only one would send the
+ // user round the loop twice.
+ 'Install the sandbox dependencies with your package manager, e.g. `sudo apt install bubblewrap ripgrep`, then retry.'
+ : windowsInstallInstructions(undefined),
+ status: 'not-installable',
+ };
+ }
+
+ const { getSrtWinPath, installWindowsSandbox, resolveSrtWin } =
+ await import('@anthropic-ai/sandbox-runtime');
+ const { ensureStagedSrtWin, resolveSrtWinSource } = await import('./srtWinStaging');
+
+ // Stage the helper as part of setup, not lazily at first use: this is the
+ // moment the user asked us to make the machine ready, and a first run that
+ // failed on file permissions would look like the setup itself hadn't worked.
+ const source = resolveSrtWinSource(getSrtWinPath);
+ const staged = source ? ensureStagedSrtWin(source) : undefined;
+ const srtWin = staged ? resolveSrtWin({ path: staged }) : undefined;
+
+ const result = installWindowsSandbox(srtWin ? { srtWin } : {});
+ return result.cancelled ? { status: 'cancelled' } : { status: 'installed' };
+};
diff --git a/packages/device-sandbox/src/srt.ts b/packages/device-sandbox/src/srt.ts
index fb15e6c73f6..446f27beec8 100644
--- a/packages/device-sandbox/src/srt.ts
+++ b/packages/device-sandbox/src/srt.ts
@@ -1,12 +1,36 @@
import type { SandboxRuntimeConfig } from '@anthropic-ai/sandbox-runtime';
+import { getSrtWinPath } from '@anthropic-ai/sandbox-runtime';
import { normalizeSandboxPolicy } from './policy';
+import { ensureStagedSrtWin, resolveSrtWinSource } from './srtWinStaging';
import type { SandboxPolicy } from './types';
+/**
+ * Point the backend at a helper the sandbox user can read. See
+ * {@link ensureStagedSrtWin} โ€” without this, a per-user app install puts the
+ * helper somewhere the sandbox account has no rights to, and every launch dies
+ * with an unexplained ACCESS_DENIED.
+ *
+ * Silent no-op off Windows and whenever staging isn't possible; the backend
+ * then resolves its own packaged binary exactly as before.
+ */
+const resolveWindowsConfig = (): SandboxRuntimeConfig['windows'] => {
+ if (process.platform !== 'win32') return undefined;
+ try {
+ const source = resolveSrtWinSource(getSrtWinPath);
+ const staged = source ? ensureStagedSrtWin(source) : undefined;
+ return staged ? { srtWin: { path: staged } } : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
export const createSrtConfig = (input: SandboxPolicy): SandboxRuntimeConfig => {
const policy = normalizeSandboxPolicy(input);
+ const windows = resolveWindowsConfig();
return {
+ ...(windows ? { windows } : {}),
filesystem: {
allowRead: [...(policy.readableRoots ?? [])],
allowWrite: [...policy.writableRoots],
diff --git a/packages/device-sandbox/src/srtWinStaging.ts b/packages/device-sandbox/src/srtWinStaging.ts
new file mode 100644
index 00000000000..f182383d1d0
--- /dev/null
+++ b/packages/device-sandbox/src/srtWinStaging.ts
@@ -0,0 +1,126 @@
+import fs from 'node:fs';
+import path from 'node:path';
+
+/**
+ * Where the relocated helper lives. Under `ProgramData` because its default ACL
+ * grants `BUILTIN\Users` read+execute โ€” which is the entire point.
+ */
+const stagingRoot = (): string =>
+ path.join(process.env.PROGRAMDATA || 'C:\\ProgramData', 'LobeHub', 'sandbox');
+
+const ARCH_DIR: Partial<Record<string, string>> = { arm64: 'arm64', x64: 'x64' };
+
+/**
+ * Locate the helper binary shipped with this app.
+ *
+ * The backend's own `getSrtWinPath()` resolves relative to its package
+ * directory, which stops being true the moment its JavaScript is bundled into
+ * the main process โ€” the computed path then points inside the bundle rather
+ * than at any real file. A packaged app therefore has to be told where its own
+ * resources are, and the desktop ships the binaries under
+ * `resources/sandbox-runtime/vendor`.
+ *
+ * Ordered most- to least-explicit; `process.resourcesPath` is undefined outside
+ * a packaged Electron app, so development and tests fall through to the
+ * backend's own lookup.
+ */
+export const resolveSrtWinSource = (packagedFallback?: () => string): string | undefined => {
+ const fromEnv = process.env.LOBE_SRT_WIN_PATH;
+ if (fromEnv && fs.existsSync(fromEnv)) return fromEnv;
+
+ const resourcesPath = (process as { resourcesPath?: string }).resourcesPath;
+ const arch = ARCH_DIR[process.arch];
+ if (resourcesPath && arch) {
+ const packaged = path.join(
+ resourcesPath,
+ 'sandbox-runtime',
+ 'vendor',
+ 'srt-win',
+ arch,
+ 'srt-win.exe',
+ );
+ if (fs.existsSync(packaged)) return packaged;
+ }
+
+ try {
+ return packagedFallback?.();
+ } catch {
+ return undefined;
+ }
+};
+
+/**
+ * Version the staged copy so an app update cannot leave a stale helper behind:
+ * a newer runtime gets a new directory rather than silently reusing the old
+ * binary. Read from the package that owns the binary, so it tracks the real
+ * artifact instead of anything we'd have to remember to bump.
+ */
+const resolveVersion = (packagedExe: string): string => {
+ // <pkgRoot>/vendor/srt-win/<arch>/srt-win.exe
+ const pkgRoot = path.resolve(path.dirname(packagedExe), '../../..');
+ try {
+ const pkg = JSON.parse(fs.readFileSync(path.join(pkgRoot, 'package.json'), 'utf8'));
+ if (typeof pkg.version === 'string' && pkg.version) return pkg.version;
+ } catch {
+ // fall through
+ }
+ // Size is a weak but honest fallback: it changes with the binary, and a
+ // collision only costs us a re-check that the copy already matches.
+ return `size-${fs.statSync(packagedExe).size}`;
+};
+
+/**
+ * Copy the Windows sandbox helper somewhere the sandbox user can actually read,
+ * and return that path.
+ *
+ * The sandbox runs the child as a *separate local account*, so every binary in
+ * the launch chain must be readable by that account โ€” not just by the person
+ * running the app. The desktop app installs per-user by default, landing the
+ * packaged helper under `C:\Users\<name>\AppData\Local\โ€ฆ`, a tree no other
+ * local account may read. `CreateProcessWithLogonW` then logs the sandbox user
+ * on successfully and fails at process creation with a bare ACCESS_DENIED,
+ * which reads like a broken sandbox rather than a file-permission problem.
+ * Confirmed on a real host: same binary, same machine, works from
+ * `ProgramData` and fails from the user profile.
+ *
+ * Relocating is the supported fix โ€” the backend takes a `windows.srtWin.path`
+ * override precisely so embedders can place the helper themselves. Granting the
+ * sandbox account an ACE on the install directory would work too, but a
+ * per-user install directory is replaced wholesale on update, taking the ACE
+ * with it and silently breaking the sandbox again.
+ *
+ * Returns `undefined` on anything other than Windows (nothing to relocate) and
+ * whenever staging fails โ€” callers then fall back to the packaged binary, which
+ * is the current behaviour, not a regression.
+ */
+export const ensureStagedSrtWin = (packagedExe: string): string | undefined => {
+ if (process.platform !== 'win32') return undefined;
+
+ try {
+ const target = path.join(
+ stagingRoot(),
+ `srt-win-${resolveVersion(packagedExe)}`,
+ 'srt-win.exe',
+ );
+
+ // Size match is enough to treat the copy as current: the directory is
+ // already version-scoped, so this only guards a truncated or half-written
+ // file from a previous interrupted copy.
+ const source = fs.statSync(packagedExe);
+ if (fs.existsSync(target) && fs.statSync(target).size === source.size) return target;
+
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ // Copy via a temp name in the same directory so a concurrent launch never
+ // observes a partially written executable.
+ const pending = `${target}.${process.pid}.tmp`;
+ fs.copyFileSync(packagedExe, pending);
+ fs.renameSync(pending, target);
+ return target;
+ } catch {
+ // Another user on this machine may own the staged copy, ProgramData may be
+ // locked down, the disk may be full. None of that should take the whole
+ // feature down โ€” fall back and let the caller fail loudly at launch if the
+ // packaged path really is unreachable.
+ return undefined;
+ }
+};
diff --git a/packages/device-sandbox/src/types.ts b/packages/device-sandbox/src/types.ts
index c970010bea1..668febab6f0 100644
--- a/packages/device-sandbox/src/types.ts
+++ b/packages/device-sandbox/src/types.ts
@@ -23,6 +23,21 @@ export interface SandboxCapability {
warnings?: string[];
}
+/**
+ * Outcome of provisioning the sandbox backend on this machine.
+ *
+ * `cancelled` is deliberately not an error: the Windows setup raises a UAC
+ * prompt, and dismissing it is the user declining, so the caller should leave
+ * the UI untouched rather than report a failure.
+ */
+export type SandboxSetupStatus = 'cancelled' | 'installed' | 'not-installable';
+
+export interface SandboxSetupResult {
+ /** What to do by hand when `status` is `not-installable`. */
+ instructions?: string;
+ status: SandboxSetupStatus;
+}
+
export interface SandboxCommand {
args: string[];
cmd: string;
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index f74d365ad6e..57ee51364f6 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -319,9 +319,63 @@ export interface RunCommandParams {
/** Merged into the child process environment (after `process.env`). */
env?: Record<string, string>;
run_in_background?: boolean;
+ /**
+ * Run this command inside the device sandbox (writes confined to `cwd` + the
+ * OS temp dir, no network). Set by the caller that knows the agent picked the
+ * "Local Sandbox" execution environment โ€” the server device-proxy for
+ * gateway-routed runs, the client executor for in-process desktop runs. The
+ * model never supplies it: the manifest doesn't expose it, and it is a
+ * user-owned security decision, not a per-call one.
+ *
+ * Absent/false keeps the historical unsandboxed path, so nothing changes for
+ * agents that never opted in. When true the sandbox is mandatory โ€” a host
+ * that cannot provide one fails the command instead of downgrading.
+ */
+ sandbox?: boolean;
+ /**
+ * Let a sandboxed command reach the package-registry allowlist. Ignored
+ * unless `sandbox` is true. Never means "the network is open" โ€” the backend
+ * refuses a catch-all allowlist, so this opens a fixed, named set of
+ * registries and forges and nothing else.
+ */
+ sandboxNetwork?: boolean;
timeout?: number;
}
+/**
+ * Whether this device can actually run sandboxed commands, as reported by the
+ * desktop main process. The renderer needs the real answer (not a platform
+ * guess) before offering the "Local Sandbox" option: SRT supports macOS and
+ * Linux only, and on Linux it additionally depends on host binaries that may be
+ * missing.
+ */
+export interface DeviceSandboxCapabilityResult {
+ available: boolean;
+ /**
+ * The app can provision the backend itself on this host (one UAC prompt on
+ * Windows). Lets the UI offer a setup button instead of a dead end โ€” a user
+ * who installed the desktop app should not have to run anything by hand
+ * before the sandbox works.
+ */
+ canInstall: boolean;
+ /** What to do by hand when the app cannot install it (e.g. Linux packages). */
+ instructions?: string;
+ /** Human-readable explanation when `available` is false. */
+ reason?: string;
+}
+
+/**
+ * Result of a user-initiated sandbox setup, plus the capability re-read
+ * afterwards so the caller never has to guess whether it took.
+ */
+export interface DeviceSandboxInstallResult {
+ capability: DeviceSandboxCapabilityResult;
+ /** Failure detail when `status` is `failed`. */
+ error?: string;
+ /** `cancelled` means the user dismissed the elevation prompt โ€” not a failure. */
+ status: 'cancelled' | 'failed' | 'installed' | 'not-installable';
+}
+
export interface RunCommandResult {
duration_ms?: number;
error?: string;
@@ -331,6 +385,11 @@ export interface RunCommandResult {
stderr: { path: string; size: number; truncated: boolean };
stdout: { path: string; size: number; truncated: boolean };
};
+ /**
+ * Whether the command was actually confined by the device sandbox โ€” what
+ * happened, not what was requested. Absent when no sandbox was asked for.
+ */
+ sandboxed?: boolean;
shell_id?: string;
stderr?: string;
stdout?: string;
diff --git a/packages/local-file-shell/src/shell/__tests__/runner.test.ts b/packages/local-file-shell/src/shell/__tests__/runner.test.ts
index 7fae29c10a5..d1c4aa05544 100644
--- a/packages/local-file-shell/src/shell/__tests__/runner.test.ts
+++ b/packages/local-file-shell/src/shell/__tests__/runner.test.ts
@@ -143,6 +143,10 @@ describe('runCommand', () => {
expect(result).toMatchObject({ exit_code: 0, success: true });
expect(fs.readFileSync(target, 'utf8')).toBe('sandbox-disabled');
+ // An unsandboxed run must not look sandboxed to anything reading the
+ // result โ€” that field is the only observable difference between "fenced"
+ // and "the request said fenced".
+ expect(result.sandboxed).toBeUndefined();
});
it.skipIf(process.platform !== 'darwin')(
diff --git a/packages/local-file-shell/src/shell/runner.ts b/packages/local-file-shell/src/shell/runner.ts
index 13c65d3f787..b71790fa21e 100644
--- a/packages/local-file-shell/src/shell/runner.ts
+++ b/packages/local-file-shell/src/shell/runner.ts
@@ -12,6 +12,19 @@ export interface RunCommandOptions {
error: (...args: any[]) => void;
info: (...args: any[]) => void;
};
+ /**
+ * The sandbox could not be established for this command (unsupported host,
+ * missing dependency, a runtime that refused the policy). Fired only for
+ * failures raised while building the launch plan โ€” never for a command that
+ * ran sandboxed and exited non-zero.
+ *
+ * Exists because the cheap capability probe is not the whole truth: the
+ * backend can report itself available and still fail when the first real
+ * process is spawned (the egress fence is only verified then). Callers use
+ * this to downgrade what they advertise instead of offering an environment
+ * that fails on every command.
+ */
+ onSandboxUnavailable?: (error: Error) => void;
processManager: ShellProcessManager;
sandboxPolicy?: SandboxPolicy;
}
@@ -25,7 +38,7 @@ export async function runCommand(
run_in_background,
timeout = 30_000,
}: RunCommandParams,
- { processManager, logger, sandboxPolicy }: RunCommandOptions,
+ { processManager, logger, onSandboxUnavailable, sandboxPolicy }: RunCommandOptions,
): Promise<RunCommandResult> {
if (!command) {
return { error: 'command is required', success: false };
@@ -48,6 +61,9 @@ export async function runCommand(
const shellConfig = await getShellConfig(effectiveCommand);
let outputFiles: ShellOutputFiles | undefined;
let releaseSandbox: (() => void) | undefined;
+ // What actually happened, reported back so nothing downstream has to infer a
+ // security property from the request that asked for it.
+ let sandboxed: boolean | undefined;
try {
let launchCommand = shellConfig;
@@ -57,15 +73,26 @@ export async function runCommand(
// explicitly supplies a policy, and avoid loading the experimental runtime on the default path.
if (sandboxPolicy) {
const { createSandboxLaunchPlan } = await import('@lobechat/device-sandbox');
- const launchPlan = await createSandboxLaunchPlan({
- command: shellConfig,
- cwd,
- env: requestedEnv,
- policy: sandboxPolicy,
- });
+ // Narrow try/catch: only a failure to BUILD the sandbox counts as the
+ // sandbox being unavailable. Everything after this โ€” spawn errors, a
+ // non-zero exit โ€” is the command's own failure and must not make the
+ // caller think the environment is broken.
+ let launchPlan;
+ try {
+ launchPlan = await createSandboxLaunchPlan({
+ command: shellConfig,
+ cwd,
+ env: requestedEnv,
+ policy: sandboxPolicy,
+ });
+ } catch (error) {
+ onSandboxUnavailable?.(error as Error);
+ throw error;
+ }
launchCommand = launchPlan;
launchEnv = launchPlan.env as NodeJS.ProcessEnv;
releaseSandbox = launchPlan.release;
+ sandboxed = launchPlan.sandboxed;
}
const shellId = processManager.createShellId();
const shellOutputFiles = processManager.createOutputFiles(shellId);
@@ -116,6 +143,7 @@ export async function runCommand(
return {
output: '',
output_files: processManager.getOutputFilesInfo(shellOutputFiles),
+ sandboxed,
shell_id: shellId,
success: true,
};
@@ -128,6 +156,7 @@ export async function runCommand(
return {
...observation,
+ sandboxed,
shell_id: shellId,
};
} catch (error) {
diff --git a/packages/local-file-shell/src/types.ts b/packages/local-file-shell/src/types.ts
index 60d7d1ecddf..74abafb1c58 100644
--- a/packages/local-file-shell/src/types.ts
+++ b/packages/local-file-shell/src/types.ts
@@ -27,6 +27,18 @@ export interface RunCommandResult {
stderr: { path: string; size: number; truncated: boolean };
stdout: { path: string; size: number; truncated: boolean };
};
+ /**
+ * Whether this command was actually confined by the device sandbox.
+ *
+ * Reports what HAPPENED, not what was configured. The picker's chip shows the
+ * user's intent, and intent is not proof: the flag has to survive every layer
+ * between the config and the spawn, and a run that lost it on the way would
+ * otherwise look identical to a fenced one. A security guarantee nobody can
+ * observe is a guarantee nobody should trust โ€” so an unfenced run says so.
+ *
+ * Absent on a request that never asked for a sandbox.
+ */
+ sandboxed?: boolean;
/**
* Session identifier. Present for background commands and foreground commands
* that can be resumed with `getCommandOutput`.
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index bb55239ddb6..190ee97cb56 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -519,6 +519,15 @@ export default {
'heteroAgent.executionTarget.loading': 'Loading devicesโ€ฆ',
'heteroAgent.executionTarget.local': 'Local device',
'heteroAgent.executionTarget.localDesc': 'Run as a local process on this desktop app',
+ 'heteroAgent.executionTarget.localSandbox': 'Local sandbox',
+ 'heteroAgent.executionTarget.localSandboxDesc':
+ 'Run on this computer, with commands limited to the working directory and no network',
+ 'heteroAgent.executionTarget.localSandboxDescNetwork':
+ 'Run on this computer, with commands limited to the working directory and to common developer domains',
+ 'heteroAgent.executionTarget.localSandboxSetUp': 'Set up',
+ 'heteroAgent.executionTarget.localSandboxNetworkTip':
+ 'Let sandboxed commands reach package registries and source forges โ€” npm, PyPI, crates.io, RubyGems, Go, GitHub, GitLab. Every other domain stays blocked; the sandbox cannot open the network entirely.',
+ 'heteroAgent.executionTarget.localSandboxUnavailable': 'Not available on this device: {{reason}}',
'heteroAgent.executionTarget.manage': 'Manage',
'heteroAgent.executionTarget.noDevices':
'No remote devices yet. Run `lh connect` on another machine to add one.',
diff --git a/packages/tool-runtime/src/ComputerRuntime.ts b/packages/tool-runtime/src/ComputerRuntime.ts
index 7c196271928..64f4deb4fc7 100644
--- a/packages/tool-runtime/src/ComputerRuntime.ts
+++ b/packages/tool-runtime/src/ComputerRuntime.ts
@@ -345,6 +345,7 @@ export abstract class ComputerRuntime {
isBackground: args.background || false,
output: r.output,
outputFiles,
+ sandboxed: r.sandboxed,
stderr: r.stderr,
stdout: r.stdout,
success: commandSuccess,
diff --git a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
index 93095a5cb55..3e7c4678208 100644
--- a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
+++ b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
@@ -416,6 +416,10 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {
commandId: raw.shell_id,
durationMs: raw.duration_ms,
outputFiles: raw.output_files,
+ // Carried through so the run itself can say whether it was fenced.
+ // The picker's chip only shows the user's intent, and a run that
+ // lost the flag somewhere in between looks identical otherwise.
+ sandboxed: raw.sandboxed,
stderr: raw.stderr,
stdout: raw.stdout,
success: raw.success,
diff --git a/packages/tool-runtime/src/types.ts b/packages/tool-runtime/src/types.ts
index b804fcf21ad..3c3d87e48f9 100644
--- a/packages/tool-runtime/src/types.ts
+++ b/packages/tool-runtime/src/types.ts
@@ -261,6 +261,16 @@ export interface RunCommandState {
stderr: { path: string; size: number; truncated: boolean };
stdout: { path: string; size: number; truncated: boolean };
};
+ /**
+ * Whether the device sandbox actually confined this command.
+ *
+ * The execution-environment chip states the user's *intent*; this states the
+ * outcome. They can differ โ€” a run routed somewhere the sandbox flag never
+ * reached executes unfenced while the chip still reads "Local sandbox" โ€” and
+ * a security property nobody can observe is one nobody should trust.
+ * Undefined when no sandbox was requested.
+ */
+ sandboxed?: boolean;
stderr?: string;
stdout?: string;
success: boolean;
diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.ts
index 8fa6366f715..e37f31d9886 100644
--- a/packages/types/src/agent/agencyConfig.ts
+++ b/packages/types/src/agent/agencyConfig.ts
@@ -754,6 +754,38 @@ export interface LobeAgentAgencyConfig {
*/
executionTargetSelectionPolicy?: ExecutionTargetSelectionPolicy;
heterogeneousProvider?: HeterogeneousProviderConfig;
+ /**
+ * Confine the run's shell commands to the device sandbox. A *modifier* on
+ * `executionTarget: 'local'`, not a target of its own โ€” the run still goes to
+ * the same machine through the same routing, it is only what the spawned
+ * command may touch that changes (writes limited to the working directory,
+ * no network).
+ *
+ * Modelled as a flag rather than a sixth `DeviceExecutionTarget` deliberately:
+ * every existing routing rule (web coercion, gateway upgrade, bot-trigger
+ * promotion, fixed-workspace policy) stays literally unchanged, and the flag
+ * composes if sandboxed execution later extends to `device` targets.
+ *
+ * Only shell commands are affected. File tools (`writeFile` / `editFile`) run
+ * in the desktop process itself, and heterogeneous CLI agents spawn through
+ * their own path โ€” neither passes through the sandboxed runner. Say
+ * "commands" in user-facing copy, never "the agent".
+ */
+ localSandbox?: boolean;
+ /**
+ * Let the sandboxed commands reach the package-registry allowlist. Only
+ * meaningful with {@link localSandbox}; defaults to off.
+ *
+ * A separate field rather than a tri-state on `localSandbox` because the two
+ * answer different questions ("fence this?" vs "may the fence let installs
+ * through?"), and because the network choice must survive toggling the
+ * sandbox off and back on.
+ *
+ * Never means "the network is open" โ€” the sandbox backend rejects a catch-all
+ * allowlist outright, so this opens a fixed set of registries and forges.
+ * User-facing copy must not promise more than that.
+ */
+ localSandboxNetwork?: boolean;
/**
* Workspace model-selection policy. `fixed` keeps the shared agent model
* authoritative; `member` enables a per-user model override stored in
@@ -841,6 +873,9 @@ export const DEFAULT_WORKSPACE_AGENT_SELECTION_POLICIES = {
* - `fixed` shared config ignores the caller override entirely
* - `override.executionTarget` wins when set; falls back to shared
* - `override.boundDeviceId` wins when set; falls back to shared
+ * - `override.localSandbox` wins when set; falls back to shared. It rides along
+ * with the target because it qualifies *this member's* local execution โ€” one
+ * member sandboxing their own machine says nothing about anyone else's.
* - Nothing else (heterogeneousProvider, verifyRubricId, workingDirByDevice)
* is overridable โ€” those describe the agent, not this user's routing
*
@@ -850,18 +885,31 @@ export const DEFAULT_WORKSPACE_AGENT_SELECTION_POLICIES = {
*/
export const resolveAgencyConfig = (
agencyConfig: LobeAgentAgencyConfig | null | undefined,
- override: Pick<LobeAgentAgencyConfig, 'boundDeviceId' | 'executionTarget'> | null | undefined,
+ override:
+ | Pick<
+ LobeAgentAgencyConfig,
+ 'boundDeviceId' | 'executionTarget' | 'localSandbox' | 'localSandboxNetwork'
+ >
+ | null
+ | undefined,
): LobeAgentAgencyConfig | undefined => {
const base = normalizeAgencyConfigHeterogeneousProvider(agencyConfig);
if (base?.executionTargetSelectionPolicy === 'fixed') return base;
if (!override) return base;
const hasTarget = override.executionTarget !== undefined;
const hasDevice = override.boundDeviceId !== undefined;
- if (!hasTarget && !hasDevice) return base;
+ // `false` is a real value here โ€” a member turning the sandbox (or its network
+ // allowance) back off must override a shared `true`, so test for presence,
+ // not truthiness.
+ const hasLocalSandbox = override.localSandbox !== undefined;
+ const hasLocalSandboxNetwork = override.localSandboxNetwork !== undefined;
+ if (!hasTarget && !hasDevice && !hasLocalSandbox && !hasLocalSandboxNetwork) return base;
return {
...base,
...(hasTarget ? { executionTarget: override.executionTarget } : {}),
...(hasDevice ? { boundDeviceId: override.boundDeviceId } : {}),
+ ...(hasLocalSandbox ? { localSandbox: override.localSandbox } : {}),
+ ...(hasLocalSandboxNetwork ? { localSandboxNetwork: override.localSandboxNetwork } : {}),
};
};
@@ -882,7 +930,13 @@ export interface AgentAgencyConfigContext {
*/
export const resolveAgentAgencyConfig = (
agencyConfig: LobeAgentAgencyConfig | null | undefined,
- override: Pick<LobeAgentAgencyConfig, 'boundDeviceId' | 'executionTarget'> | null | undefined,
+ override:
+ | Pick<
+ LobeAgentAgencyConfig,
+ 'boundDeviceId' | 'executionTarget' | 'localSandbox' | 'localSandboxNetwork'
+ >
+ | null
+ | undefined,
context: AgentAgencyConfigContext,
): LobeAgentAgencyConfig | undefined => {
const base = normalizeAgencyConfigHeterogeneousProvider(agencyConfig);
diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.ts
index 0b28fd33837..a18120cf6cc 100644
--- a/packages/types/src/tool/builtin.ts
+++ b/packages/types/src/tool/builtin.ts
@@ -612,6 +612,24 @@ export interface BuiltinToolContext {
*/
isSubAgent?: boolean;
+ /**
+ * The run executes on this machine AND its owner asked for the device sandbox
+ * (`agencyConfig.localSandbox` on a `local` target). The Local System executor
+ * forwards it to `runCommand` so the desktop confines the spawned command.
+ *
+ * Resolved by the caller that builds this context โ€” the executor must not
+ * re-derive it, so the in-process path and the server device-proxy stay in
+ * agreement about which runs are fenced.
+ */
+ localSandbox?: boolean;
+
+ /**
+ * The fenced run may reach the package-registry allowlist
+ * (`agencyConfig.localSandboxNetwork`). Meaningless without
+ * {@link localSandbox}.
+ */
+ localSandboxNetwork?: boolean;
+
/**
* Tool execution context key. It is the tool message ID for locally persisted
* tool messages, but gateway execution can temporarily use the toolCallId
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.ts
index e1c1c3fd59f..ce67d9d6c14 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -19,7 +19,9 @@ import type { NotificationSettings } from './settings/notification';
* another. See `resolveAgencyConfig` in
* `packages/types/src/agent/agencyConfig.ts` for the merge implementation.
*
- * Two fields only, deliberately: `executionTarget` + `boundDeviceId`.
+ * Routing fields only, deliberately: `executionTarget`, `boundDeviceId`, and
+ * the two `localSandbox*` fields (which qualify *this member's* local execution
+ * โ€” how hard their own machine is fenced is theirs to decide).
* `heterogeneousProvider`, `verifyRubricId`, and `workingDirByDevice` remain
* agent-shared because they describe *what the agent is*, not *how this user
* routes it*.
@@ -27,6 +29,8 @@ import type { NotificationSettings } from './settings/notification';
export interface AgentDeviceOverride {
boundDeviceId?: string;
executionTarget?: DeviceExecutionTarget;
+ localSandbox?: boolean;
+ localSandboxNetwork?: boolean;
}
/**
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index 73450e03c63..4ef88e4d14f 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -4,6 +4,7 @@ import { isDesktop } from '@lobechat/const';
import { HETEROGENEOUS_TYPE_LABELS } from '@lobechat/heterogeneous-agents';
import type { DeviceExecutionTarget } from '@lobechat/types';
import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import {
CheckIcon,
@@ -12,12 +13,15 @@ import {
InfoIcon,
MonitorDownIcon,
SettingsIcon,
+ ShieldCheckIcon,
} from 'lucide-react';
import { memo, type ReactNode, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import InstantSwitch from '@/components/InstantSwitch';
import { DOWNLOAD_URL } from '@/const/url';
import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';
+import { useLocalSandboxCapability } from '@/features/ChatInput/hooks/useLocalSandboxCapability';
import { useSelectExecutionTarget } from '@/features/ChatInput/hooks/useSelectExecutionTarget';
import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
import {
@@ -28,10 +32,12 @@ import {
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import {
isHeterogeneousSandboxExecutionAvailable,
+ isLocalSandboxEnabled,
resolveExecutionTarget,
} from '@/helpers/executionTarget';
import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
+import { localFileService } from '@/services/electron/localFileService';
import { useAgentStore } from '@/store/agent';
import { useElectronStore } from '@/store/electron';
@@ -88,6 +94,32 @@ const styles = createStaticStyles(({ css }) => ({
font-size: 11px;
color: ${cssVar.colorTextDescription};
`,
+ extra: css`
+ display: flex;
+ flex: none;
+ gap: 4px;
+ align-items: center;
+
+ margin-inline-start: auto;
+
+ /* A disabled row dims itself, but its trailing action is the way OUT of
+ that state โ€” dimming the setup button would read as "also unavailable". */
+ opacity: 1;
+ `,
+ extraInfo: css`
+ cursor: help;
+
+ display: flex;
+ align-items: center;
+
+ color: ${cssVar.colorTextQuaternary};
+
+ transition: color 0.2s;
+
+ &:hover {
+ color: ${cssVar.colorTextSecondary};
+ }
+ `,
deviceList: css`
overflow-y: auto;
@@ -277,36 +309,54 @@ interface OptionRowProps {
active: boolean;
desc?: ReactNode;
disabled?: boolean;
+ /**
+ * Trailing controls that belong to the row but are not the row's selection โ€”
+ * rendered before the checkmark, with clicks kept from selecting the row so a
+ * setting can be adjusted without switching environment.
+ */
+ extra?: ReactNode;
icon: ReactNode;
label: string;
onClick: () => void;
tag?: ReactNode;
}
-const OptionRow = memo<OptionRowProps>(({ active, desc, disabled, icon, label, onClick, tag }) => {
- return (
- <div
- className={cx(
- styles.option,
- active && styles.optionActive,
- disabled && styles.optionDisabled,
- )}
- onClick={() => {
- if (!disabled) onClick();
- }}
- >
- <div className={styles.optionIcon}>{icon}</div>
- <div className={styles.optionMeta}>
- <Flexbox horizontal align={'center'} gap={6}>
- <span className={styles.optionTitle}>{label}</span>
- {tag ? <span className={styles.tag}>{tag}</span> : null}
- </Flexbox>
- {desc ? <div className={styles.desc}>{desc}</div> : null}
+const OptionRow = memo<OptionRowProps>(
+ ({ active, desc, disabled, extra, icon, label, onClick, tag }) => {
+ return (
+ <div
+ className={cx(
+ styles.option,
+ active && styles.optionActive,
+ disabled && styles.optionDisabled,
+ )}
+ onClick={() => {
+ if (!disabled) onClick();
+ }}
+ >
+ <div className={styles.optionIcon}>{icon}</div>
+ <div className={styles.optionMeta}>
+ <Flexbox horizontal align={'center'} gap={6}>
+ <span className={styles.optionTitle}>{label}</span>
+ {tag ? <span className={styles.tag}>{tag}</span> : null}
+ </Flexbox>
+ {desc ? <div className={styles.desc}>{desc}</div> : null}
+ </div>
+ {extra ? (
+ <div
+ className={styles.extra}
+ onClick={(event) => {
+ event.stopPropagation();
+ }}
+ >
+ {extra}
+ </div>
+ ) : null}
+ {active ? <Icon className={styles.check} icon={CheckIcon} size={14} /> : null}
</div>
- {active ? <Icon className={styles.check} icon={CheckIcon} size={14} /> : null}
- </div>
- );
-});
+ );
+ },
+);
OptionRow.displayName = 'HeteroDeviceSwitcher.OptionRow';
@@ -390,15 +440,64 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
supportsSandbox,
]);
+ // The sandbox is a modifier on `local`, not a target of its own, so the two
+ // local rows differ only by this flag. Reading it through the same helper the
+ // server and the desktop runner use keeps the checkmark honest: it lights up
+ // exactly when a command would actually be fenced.
+ const localSandboxEnabled = isLocalSandboxEnabled(agencyConfig, executionTarget);
+ const localSandboxNetwork = agencyConfig?.localSandboxNetwork === true;
+ const { data: sandboxCapability, mutate: revalidateSandboxCapability } =
+ useLocalSandboxCapability();
+ const canUseLocalSandbox = sandboxCapability?.available === true;
+
+ // The desktop downgrades its own verdict when a fence fails to establish (the
+ // cheap probe can't see that far), so re-ask each time the picker opens
+ // instead of showing a stale "available" for the rest of the session.
+ useEffect(() => {
+ if (!isDesktop || !open) return;
+ void revalidateSandboxCapability();
+ }, [open, revalidateSandboxCapability]);
+
const selectExecutionTarget = useSelectExecutionTarget(agentId);
const handleSelect = useCallback(
- async (target: DeviceExecutionTarget, deviceId?: string) => {
+ async (target: DeviceExecutionTarget, deviceId?: string, localSandbox?: boolean) => {
setOpen(false);
- await selectExecutionTarget(target, deviceId);
+ await selectExecutionTarget(target, deviceId, { localSandbox });
},
[selectExecutionTarget],
);
+ // Setting up the backend raises an elevation prompt and creates a dedicated
+ // OS account, so it only ever happens on this explicit click. The popover
+ // stays open throughout โ€” the user came here to pick an environment, and the
+ // row turning usable is the answer to what they clicked.
+ const [isInstallingSandbox, setIsInstallingSandbox] = useState(false);
+ const handleInstallSandbox = useCallback(async () => {
+ setIsInstallingSandbox(true);
+ try {
+ const result = await localFileService.installSandbox();
+ // The IPC already re-probed, so trust its verdict rather than firing
+ // another round-trip. A cancelled prompt lands here too, with the
+ // unchanged capability โ€” nothing to report, the user just said no.
+ await revalidateSandboxCapability(result.capability, { revalidate: false });
+ } finally {
+ setIsInstallingSandbox(false);
+ }
+ }, [revalidateSandboxCapability]);
+
+ // Toggling the network does NOT change which environment is selected โ€” same
+ // dormant semantics the sandbox flag itself has when another environment is
+ // active, so the popover stays open and nothing is switched behind the user.
+ const handleToggleSandboxNetwork = useCallback(
+ async (enabled: boolean) => {
+ await selectExecutionTarget(executionTarget, boundDeviceId, {
+ localSandbox: localSandboxEnabled,
+ localSandboxNetwork: enabled,
+ });
+ },
+ [selectExecutionTarget, executionTarget, boundDeviceId, localSandboxEnabled],
+ );
+
// Auto-default to THIS desktop's local execution on first open, for both
// personal and workspace agents (workspace behaviour used to be a hostname
// lookup against the workspace device pool โ€” see โ€” but with
@@ -497,6 +596,12 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
? 'heteroAgent.executionTarget.local'
: 'heteroAgent.executionTarget.workspaceGroup',
);
+ // A fenced run looks identical to an unfenced one until a command fails, so
+ // the chip โ€” the only always-visible surface โ€” has to say which it is.
+ if (canShowExecutionTargetSelector && localSandboxEnabled) {
+ chipIcon = <Icon icon={ShieldCheckIcon} size={14} />;
+ chipLabel = t('heteroAgent.executionTarget.localSandbox');
+ }
} else if (chipExecutionTarget === 'device') {
chipIcon = <ExecutionTargetIcon devicePlatform={boundDevice?.platform} target={'device'} />;
chipLabel = canShowExecutionTargetSelector
@@ -508,6 +613,9 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
const isActive = (target: DeviceExecutionTarget, deviceId?: string) => {
if (target === 'device') return executionTarget === 'device' && boundDeviceId === deviceId;
+ // The two local rows share one target and are told apart by the sandbox
+ // flag, so neither may claim the checkmark on the other's behalf.
+ if (target === 'local') return executionTarget === 'local' && !localSandboxEnabled;
return executionTarget === target;
};
@@ -602,7 +710,58 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
icon={<ExecutionTargetIcon target={'local'} />}
// ๆœฌๆœบ็ปŸไธ€ๆ˜พ็คบใ€Œๆœฌๅœฐ่ฎพๅค‡ใ€๏ผŒไธๅ†ๅธฆๅ…ทไฝ“่ฎพๅค‡ๅ็งฐ
label={t('heteroAgent.executionTarget.local')}
- onClick={() => void handleSelect('local')}
+ onClick={() => void handleSelect('local', undefined, false)}
+ />
+ ) : null}
+ {/* Same machine as the row above, fenced: writes confined to the working
+ directory, network denied unless the switch opens the registry
+ allowlist. Shown even when the host can't provide a sandbox โ€” disabled,
+ carrying the real reason, because "unavailable" here usually means
+ "not installed yet" and silently hiding the feature would strand the
+ user with no way to find out why. */}
+ {isDesktop ? (
+ <OptionRow
+ active={executionTarget === 'local' && localSandboxEnabled}
+ disabled={!canUseLocalSandbox}
+ icon={<Icon icon={ShieldCheckIcon} size={14} />}
+ label={t('heteroAgent.executionTarget.localSandbox')}
+ desc={
+ canUseLocalSandbox
+ ? t(
+ localSandboxNetwork
+ ? 'heteroAgent.executionTarget.localSandboxDescNetwork'
+ : 'heteroAgent.executionTarget.localSandboxDesc',
+ )
+ : // Prefer the actionable instruction (Linux's "install this
+ // package") over the backend's raw diagnostic when we have one.
+ (sandboxCapability?.instructions ??
+ t('heteroAgent.executionTarget.localSandboxUnavailable', {
+ reason: sandboxCapability?.reason ?? '',
+ }))
+ }
+ extra={
+ canUseLocalSandbox ? (
+ <>
+ <InstantSwitch
+ enabled={localSandboxNetwork}
+ size={'small'}
+ onChange={handleToggleSandboxNetwork}
+ />
+ <Tooltip title={t('heteroAgent.executionTarget.localSandboxNetworkTip')}>
+ <span className={styles.extraInfo}>
+ <Icon icon={InfoIcon} size={12} />
+ </span>
+ </Tooltip>
+ </>
+ ) : sandboxCapability?.canInstall ? (
+ // The backend is missing but we can provision it โ€” a dead-end row
+ // would leave the user to discover a CLI incantation on their own.
+ <Button loading={isInstallingSandbox} size={'small'} onClick={handleInstallSandbox}>
+ {t('heteroAgent.executionTarget.localSandboxSetUp')}
+ </Button>
+ ) : undefined
+ }
+ onClick={() => void handleSelect('local', undefined, true)}
/>
) : null}
<OptionRow
diff --git a/src/features/ChatInput/hooks/useLocalSandboxCapability.ts b/src/features/ChatInput/hooks/useLocalSandboxCapability.ts
new file mode 100644
index 00000000000..ebff8deb9c4
--- /dev/null
+++ b/src/features/ChatInput/hooks/useLocalSandboxCapability.ts
@@ -0,0 +1,31 @@
+import { isDesktop } from '@lobechat/const';
+import type { DeviceSandboxCapabilityResult } from '@lobechat/electron-client-ipc';
+import type { SWRResponse } from 'swr';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { localFileService } from '@/services/electron/localFileService';
+
+const LOCAL_SANDBOX_CAPABILITY_SWR_KEY = 'local-sandbox-capability';
+
+/**
+ * Whether this machine can actually run sandboxed commands.
+ *
+ * Asked instead of guessed: availability depends on host binaries and OS
+ * configuration, not on the platform string, so a `process.platform` check in
+ * the renderer would offer the option on hosts that cannot honour it.
+ *
+ * The verdict can change during a session โ€” in one direction. The desktop's
+ * cheap probe only checks that the backend is installed; parts of the fence are
+ * exercised only when the first real process spawns, so a host can pass the
+ * probe and still fail every command. The desktop downgrades itself when that
+ * happens, which is why callers revalidate when they are about to show the
+ * option rather than trusting the first answer forever.
+ *
+ * Web has no local machine to fence, so it never asks.
+ */
+export const useLocalSandboxCapability = (): SWRResponse<DeviceSandboxCapabilityResult> =>
+ useClientDataSWR<DeviceSandboxCapabilityResult>(
+ isDesktop ? [LOCAL_SANDBOX_CAPABILITY_SWR_KEY] : null,
+ () => localFileService.getSandboxCapability(),
+ { revalidateOnFocus: false, revalidateOnReconnect: false },
+ );
diff --git a/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts
index 1966261e659..043e0f91922 100644
--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts
+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts
@@ -15,6 +15,7 @@ const testState = vi.hoisted(() => ({
executionTargetSelectionPolicy?: 'fixed' | 'member';
executionTarget?: string;
heterogeneousProvider?: { type: string };
+ localSandbox?: boolean;
}
| undefined,
agentMap: {} as Record<
@@ -32,7 +33,10 @@ const testState = vi.hoisted(() => ({
user: {
updateWorkspaceUserPreference: vi.fn(),
workspaceUserPreference: {} as {
- agentDeviceOverrides?: Record<string, { boundDeviceId?: string; executionTarget?: string }>;
+ agentDeviceOverrides?: Record<
+ string,
+ { boundDeviceId?: string; executionTarget?: string; localSandbox?: boolean }
+ >;
},
},
}));
@@ -179,6 +183,54 @@ describe('useSelectExecutionTarget', () => {
});
});
+ it('records the sandbox choice alongside a local pick', async () => {
+ testState.isDesktop = true;
+ testState.electron.gatewayDeviceInfo = { deviceId: 'this-machine' };
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('local', undefined, { localSandbox: true });
+
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
+ agencyConfig: {
+ boundDeviceId: 'this-machine',
+ executionTarget: 'local',
+ localSandbox: true,
+ },
+ });
+ });
+
+ it('clears the sandbox when the plain local row is picked', async () => {
+ // Switching back has to be an explicit `false`, not an omission โ€” a
+ // leftover `true` would keep fencing a run the user just un-fenced.
+ testState.isDesktop = true;
+ testState.electron.gatewayDeviceInfo = { deviceId: 'this-machine' };
+ testState.agent.agencyConfig = { executionTarget: 'local', localSandbox: true };
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('local', undefined, { localSandbox: false });
+
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
+ agencyConfig: {
+ boundDeviceId: 'this-machine',
+ executionTarget: 'local',
+ localSandbox: false,
+ },
+ });
+ });
+
+ it('leaves the stored sandbox choice dormant when switching to another environment', async () => {
+ // Cloud Sandbox has no opinion about how the user's own machine is
+ // fenced, so flipping away and back must not silently forget it.
+ testState.agent.agencyConfig = { executionTarget: 'local', localSandbox: true };
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('sandbox');
+
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
+ agencyConfig: { executionTarget: 'sandbox', localSandbox: true },
+ });
+ });
+
it('does not switch a heterogeneous agent to local when no device can be resolved', async () => {
testState.agent.isHetero = true;
testState.getDeviceInfo.mockRejectedValue(new Error('no gateway'));
@@ -259,6 +311,35 @@ describe('useSelectExecutionTarget', () => {
});
});
+ it("keeps a member's own sandbox choice in their override when they switch environment", async () => {
+ // One member fencing their own machine is theirs alone โ€” it must live in
+ // the per-user override and survive a target switch, never reach the
+ // shared row where it would apply to everyone.
+ testState.user.workspaceUserPreference = {
+ agentDeviceOverrides: {
+ 'agent-id': {
+ boundDeviceId: 'this-machine',
+ executionTarget: 'local',
+ localSandbox: true,
+ },
+ },
+ };
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('sandbox');
+
+ expect(testState.user.updateWorkspaceUserPreference).toHaveBeenCalledWith({
+ agentDeviceOverrides: {
+ 'agent-id': {
+ boundDeviceId: 'this-machine',
+ executionTarget: 'sandbox',
+ localSandbox: true,
+ },
+ },
+ });
+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();
+ });
+
it('drops boundDeviceId when it cannot be resolved (e.g. web caller picks local)', async () => {
testState.isDesktop = false;
const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
diff --git a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts b/src/features/ChatInput/hooks/useSelectExecutionTarget.ts
index 44cf10b1bb7..4c8a9d6b360 100644
--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts
+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.ts
@@ -12,6 +12,21 @@ import { useElectronStore } from '@/store/electron';
import { useUserStore } from '@/store/user';
export interface SelectExecutionTargetOptions {
+ /**
+ * Confine this agent's shell commands to the device sandbox. Only meaningful
+ * alongside `target: 'local'`; the picker passes `false` for the plain local
+ * row so switching back off is an explicit write rather than a leftover.
+ *
+ * Omitted entirely for the other targets, which leaves any stored value
+ * dormant โ€” flipping to Cloud Sandbox and back must not silently forget that
+ * the user had fenced their machine.
+ */
+ localSandbox?: boolean;
+ /**
+ * Let sandboxed commands reach the package-registry allowlist. Same
+ * omitted-means-untouched rule as {@link localSandbox}.
+ */
+ localSandboxNetwork?: boolean;
/**
* The call is an automatic default (agent has no target yet), not a user's
* pick. Persistence failures stay silent โ€” a generic "your change was not
@@ -117,12 +132,24 @@ export const useSelectExecutionTarget = (agentId: string) => {
// `resolveExecutionTarget` already coerces a stored `local` +
// `boundDeviceId` to `device` when a gateway is available, so the
// server-side dispatch path Just Works โ€” no need to pre-coerce here.
+ // `undefined` leaves the stored value untouched; `false` actively clears
+ // it. Only the two local rows have an opinion, so a Cloud Sandbox pick
+ // never rewrites the fence the user set on their own machine.
+ const localSandboxPatch = {
+ ...(options?.localSandbox === undefined ? {} : { localSandbox: options.localSandbox }),
+ ...(options?.localSandboxNetwork === undefined
+ ? {}
+ : { localSandboxNetwork: options.localSandboxNetwork }),
+ };
+
if (usesWorkspaceMemberSelection) {
const nextOverrides = {
...workspaceUserPreference.agentDeviceOverrides,
[agentId]: {
+ ...workspaceUserPreference.agentDeviceOverrides?.[agentId],
executionTarget: target,
...(nextBoundDeviceId ? { boundDeviceId: nextBoundDeviceId } : {}),
+ ...localSandboxPatch,
},
};
await updateWorkspaceUserPreference({ agentDeviceOverrides: nextOverrides });
@@ -134,6 +161,7 @@ export const useSelectExecutionTarget = (agentId: string) => {
...agencyConfig,
executionTarget: target,
...(nextBoundDeviceId ? { boundDeviceId: nextBoundDeviceId } : {}),
+ ...localSandboxPatch,
},
};
diff --git a/src/helpers/executionTarget.test.ts b/src/helpers/executionTarget.test.ts
index 7aba3d8e332..ca81163f1b1 100644
--- a/src/helpers/executionTarget.test.ts
+++ b/src/helpers/executionTarget.test.ts
@@ -7,6 +7,7 @@ import {
executionTargetToRuntimeMode,
isDeviceLockedPlan,
isHeterogeneousSandboxExecutionAvailable,
+ isLocalSandboxEnabled,
resolveExecutionPlan,
resolveExecutionTarget,
resolveRuntimeMode,
@@ -1123,3 +1124,36 @@ describe('isDeviceLockedPlan', () => {
expect(isDeviceLockedPlan({ kind: 'sandbox', target: 'sandbox' })).toBe(false);
});
});
+
+describe('isLocalSandboxEnabled', () => {
+ it('fences a local run that opted in', () => {
+ expect(
+ isLocalSandboxEnabled(cfg({ executionTarget: 'local', localSandbox: true }), 'local'),
+ ).toBe(true);
+ });
+
+ it('leaves an opted-out local run alone', () => {
+ expect(isLocalSandboxEnabled(cfg({ executionTarget: 'local' }), 'local')).toBe(false);
+ expect(
+ isLocalSandboxEnabled(cfg({ executionTarget: 'local', localSandbox: false }), 'local'),
+ ).toBe(false);
+ });
+
+ it('ignores the flag once the run resolved somewhere other than local', () => {
+ // A stored `localSandbox` survives a switch to Cloud Sandbox (so switching
+ // back restores it), and web/bot coercions move a `local` target to
+ // `sandbox` / `device` / `auto`. None of those runs touch the desktop
+ // sandbox, so claiming they are fenced would be a lie about a security
+ // guarantee.
+ const config = cfg({ executionTarget: 'local', localSandbox: true });
+
+ expect(isLocalSandboxEnabled(config, 'sandbox')).toBe(false);
+ expect(isLocalSandboxEnabled(config, 'device')).toBe(false);
+ expect(isLocalSandboxEnabled(config, 'auto')).toBe(false);
+ expect(isLocalSandboxEnabled(config, 'none')).toBe(false);
+ });
+
+ it('treats a missing config as unfenced', () => {
+ expect(isLocalSandboxEnabled(undefined, 'local')).toBe(false);
+ });
+});
diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.ts
index 4919609a30c..5fb00384051 100644
--- a/src/helpers/executionTarget.ts
+++ b/src/helpers/executionTarget.ts
@@ -224,6 +224,25 @@ export const resolveExecutionTarget = (
return effective;
};
+/**
+ * Whether this run's shell commands must go through the device sandbox.
+ *
+ * The stored flag alone is not the answer: `localSandbox` qualifies *local*
+ * execution, so it applies only once the effective target actually resolved to
+ * `local`. A config that carries the flag but ran into a web coercion, a bot
+ * trigger promotion, or a `device` selection is not sandboxed โ€” pretending
+ * otherwise would claim a guarantee the run never had.
+ *
+ * Callers pass the target they already resolved (`resolveExecutionTarget` /
+ * `ExecutionPlan.target`) rather than re-deriving it, so the picker, the server
+ * device-proxy, and the desktop runner cannot drift apart on which runs are
+ * fenced.
+ */
+export const isLocalSandboxEnabled = (
+ agencyConfig: LobeAgentAgencyConfig | undefined,
+ effectiveTarget: DeviceExecutionTarget,
+): boolean => effectiveTarget === 'local' && agencyConfig?.localSandbox === true;
+
/**
* Derive the `runtimeMode` tool gate from the unified execution target:
* `local` โ†’ local-system tools, `sandbox` โ†’ cloud sandbox, `device`/`auto` โ†’
diff --git a/src/helpers/localSandbox.ts b/src/helpers/localSandbox.ts
new file mode 100644
index 00000000000..35f0c8ec972
--- /dev/null
+++ b/src/helpers/localSandbox.ts
@@ -0,0 +1,79 @@
+import { isDesktop } from '@lobechat/const';
+import type { LobeAgentAgencyConfig } from '@lobechat/types';
+import { resolveAgentAgencyConfig } from '@lobechat/types';
+
+import { isLocalSandboxEnabled, resolveExecutionTarget } from '@/helpers/executionTarget';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+import { useUserStore } from '@/store/user';
+
+export interface ClientLocalSandboxDecision {
+ /** Confine this command (writes scoped to the working directory). */
+ localSandbox: boolean;
+ /** โ€ฆand let it reach the package-registry allowlist. */
+ localSandboxNetwork: boolean;
+}
+
+const unfenced: ClientLocalSandboxDecision = { localSandbox: false, localSandboxNetwork: false };
+
+const isFenced = (agencyConfig: LobeAgentAgencyConfig | undefined): boolean =>
+ isLocalSandboxEnabled(
+ agencyConfig,
+ resolveExecutionTarget(agencyConfig, {
+ clientExecutionAvailable: true,
+ isHetero: !!agencyConfig?.heterogeneousProvider?.type,
+ }),
+ );
+
+/**
+ * Whether an in-process desktop command must be sandboxed.
+ *
+ * The gateway path resolves this on the server (`ToolExecutionContext.localSandbox`),
+ * but a desktop run that executes in-process never reaches the server runtime โ€”
+ * without this the user could pick "Local Sandbox" and get an unfenced command
+ * with no indication anything was skipped. Both paths converge on
+ * `isLocalSandboxEnabled` so they cannot disagree about which runs are fenced.
+ *
+ * Non-reactive by necessity (executors are plain callbacks, not components), so
+ * it reads the two stores `useEffectiveAgencyConfig` composes: the shared
+ * `agents.agencyConfig` plus this member's `agentDeviceOverrides` entry, merged
+ * through the same `resolveAgentAgencyConfig` the picker and server dispatch
+ * use โ€” a plain `resolveAgencyConfig` would apply a member override on a
+ * private Agent, where every other layer ignores it.
+ *
+ * One input is genuinely unavailable here: `canManage` comes from a permission
+ * hook with no store to read synchronously. It only changes the answer for an
+ * author/admin of a *public workspace* Agent carrying a stale member override,
+ * so rather than guess, both readings are computed and a disagreement resolves
+ * toward fencing. Over-fencing fails loudly and recoverably โ€” a write outside
+ * the working directory is refused with a clear error โ€” while under-fencing
+ * would run unconfined beneath a chip that claims otherwise, which is the one
+ * outcome this whole feature exists to prevent.
+ */
+export const resolveClientLocalSandbox = (agentId?: string): ClientLocalSandboxDecision => {
+ if (!isDesktop || !agentId) return unfenced;
+
+ const state = useAgentStore.getState();
+ const sharedAgencyConfig = agentByIdSelectors.getAgencyConfigById(agentId)(state);
+ const agent = agentByIdSelectors.getAgentById(agentId)(state);
+ const override = useUserStore.getState().workspaceUserPreference.agentDeviceOverrides?.[agentId];
+
+ const context = { visibility: agent?.visibility, workspaceId: agent?.workspaceId ?? undefined };
+ const asMember = resolveAgentAgencyConfig(sharedAgencyConfig, override, context);
+ const asManager = resolveAgentAgencyConfig(sharedAgencyConfig, override, {
+ ...context,
+ canManage: true,
+ });
+
+ const fenced = isFenced(asMember) || isFenced(asManager);
+ if (!fenced) return unfenced;
+
+ // Network is a relaxation of the fence, so it needs agreement rather than
+ // either-or: opening the allowlist on the strength of a reading the user may
+ // never have seen would widen what a fenced command can reach.
+ return {
+ localSandbox: true,
+ localSandboxNetwork:
+ asMember?.localSandboxNetwork === true && asManager?.localSandboxNetwork === true,
+ };
+};
diff --git a/src/services/electron/localFileService.ts b/src/services/electron/localFileService.ts
index b5c017f0b14..3a2fc746ad2 100644
--- a/src/services/electron/localFileService.ts
+++ b/src/services/electron/localFileService.ts
@@ -2,6 +2,8 @@ import { MARKDOWN_MIME_TYPES } from '@lobechat/const';
import {
type AuditSafePathsParams,
type AuditSafePathsResult,
+ type DeviceSandboxCapabilityResult,
+ type DeviceSandboxInstallResult,
type EditLocalFileParams,
type EditLocalFileResult,
type GetCommandOutputParams,
@@ -261,6 +263,23 @@ class LocalFileService {
return ensureElectronIpc().shellCommand.handleRunCommand(params);
}
+ /**
+ * Whether this machine can run sandboxed commands. Asked before offering the
+ * "Local Sandbox" execution environment โ€” the host, not the platform string,
+ * is the authority (Linux support depends on binaries that may be absent).
+ */
+ async getSandboxCapability(): Promise<DeviceSandboxCapabilityResult> {
+ return ensureElectronIpc().shellCommand.getSandboxCapability();
+ }
+
+ /**
+ * Provision the sandbox backend on this machine (one elevation prompt on
+ * Windows) and report the capability afterwards. User-initiated only.
+ */
+ async installSandbox(): Promise<DeviceSandboxInstallResult> {
+ return ensureElectronIpc().shellCommand.installSandbox();
+ }
+
async getCommandOutput(params: GetCommandOutputParams): Promise<GetCommandOutputResult> {
return ensureElectronIpc().shellCommand.handleGetCommandOutput(params);
}
diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.ts
index a93d1325c4b..e8b275f9e20 100644
--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts
+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts
@@ -6,6 +6,7 @@ import {
import debug from 'debug';
import { resolveEffectiveWorkingDirectory } from '@/helpers/effectiveWorkingDirectory';
+import { resolveClientLocalSandbox } from '@/helpers/localSandbox';
import { type MCPToolCallResult } from '@/libs/mcp';
import { mcpService } from '@/services/mcp';
import { messageService } from '@/services/message';
@@ -201,6 +202,10 @@ export class PluginTypesActionImpl {
groupId,
groupOrchestration,
isSubAgent,
+ // Only the in-process desktop path reaches here; gateway-routed runs
+ // get the same decision from the server device-proxy. Both funnel
+ // through `isLocalSandboxEnabled`, so they cannot disagree.
+ ...resolveClientLocalSandbox(agentId),
messageId: id,
operationId,
registerAfterCompletion,