diff --git a/dotnet/samples/02-agents/Harness/BuildYourOwnClaw/Claw_Step03_ScalingCapabilities/Program.cs b/dotnet/samples/02-agents/Harness/BuildYourOwnClaw/Claw_Step03_ScalingCapabilities/Program.cs index 4e69acbe126..9c9223bb19e 100644 --- a/dotnet/samples/02-agents/Harness/BuildYourOwnClaw/Claw_Step03_ScalingCapabilities/Program.cs +++ b/dotnet/samples/02-agents/Harness/BuildYourOwnClaw/Claw_Step03_ScalingCapabilities/Program.cs @@ -8,9 +8,9 @@ // 1. Skills — package finance know-how (valuation, risk-scoring) as discoverable SKILL.md // files the agent loads on demand. Optionally fold in centrally-managed Foundry // skills from a Foundry Toolbox MCP endpoint (opt-in via FOUNDRY_TOOLBOX_MCP_SERVER_URL). -// 2. Shell — a sandboxed shell, confined to the trade-confirmation vault, that the agent -// uses to reorganize the accumulated confirmation files (year/month, rename, -// archive). Guarded by a deny-list policy and a confined working directory. +// 2. Shell — a local shell that starts each command in the trade-confirmation vault, which +// the agent uses to reorganize the accumulated confirmation files (year/month, +// rename, archive). Every command needs approval; the shell is not sandboxed. // 3. CodeAct — the agent writes and runs Python to crunch portfolio numbers, in a sandboxed // Hyperlight micro-VM (needs hardware virtualization). // 4. Background agents — fan out a per-ticker research sub-agent so several tickers are researched @@ -130,13 +130,14 @@ research before making decisions. // // -// A sandboxed shell, confined to the trade-confirmation vault. ConfineWorkingDirectory re-anchors -// every command to the vault, and the deny-list policy pre-filters obviously destructive commands. -// (Patterns are a UX guardrail, not a security boundary — for hard isolation use DockerShellExecutor.) +// A local shell that starts each command in the trade-confirmation vault. By default the executor +// moves every command back to the vault before it runs, and the deny-list policy pre-filters obviously +// destructive commands. Neither is a security boundary: a command can still reach files outside the +// vault (for example with `cd ..` or an absolute path). Each command needs approval, which is the +// actual check. For hard isolation use DockerShellExecutor. await using var shellExecutor = new LocalShellExecutor(new LocalShellExecutorOptions { WorkingDirectory = vaultDir, - ConfineWorkingDirectory = true, Policy = new ShellPolicy(denyList: [ @"\brm\s+-rf\b", @@ -158,7 +159,7 @@ research before making decisions. // // Turn the chat client into a HarnessAgent. On top of Post 2's file access and approvals we add the -// four "scaling" capabilities: skills (our own provider), background agents, a confined shell, and +// four "scaling" capabilities: skills (our own provider), background agents, an approval-gated shell, and // CodeAct. // The shell is wired up in two parts: the ShellEnvironmentProvider injects OS/shell/CWD info into the // system prompt, and the shell tool is registered below in ChatOptions. @@ -188,7 +189,7 @@ research before making decisions. [ StockTools.CreateGetStockPriceTool(), TradingTools.CreatePlaceTradeTool(), - // The confined shell, exposed as the approval-gated run_shell tool. + // The local shell, exposed as the approval-gated run_shell tool. shellExecutor.AsAIFunction(requireApproval: true), ], Reasoning = new() { Effort = ReasoningEffort.Medium }, diff --git a/dotnet/samples/02-agents/Harness/BuildYourOwnClaw/Claw_Step03_ScalingCapabilities/README.md b/dotnet/samples/02-agents/Harness/BuildYourOwnClaw/Claw_Step03_ScalingCapabilities/README.md index 8aeede2fe39..a08a61815b9 100644 --- a/dotnet/samples/02-agents/Harness/BuildYourOwnClaw/Claw_Step03_ScalingCapabilities/README.md +++ b/dotnet/samples/02-agents/Harness/BuildYourOwnClaw/Claw_Step03_ScalingCapabilities/README.md @@ -13,13 +13,13 @@ It builds on Post 2's personal finance assistant and makes it *more capable* alo harness default. Optionally folds in centrally-managed **Foundry skills** discovered live from a Foundry **Toolbox MCP** endpoint via `FoundrySkills.ConnectAsync(...)` + `UseMcpSkills(...)` (opt-in; see below). -- **Shell** — a `LocalShellExecutor` confined to the trade-confirmation vault +- **Shell** — a `LocalShellExecutor` that starts each command in the trade-confirmation vault (`working/confirmations/`) lets the agent tidy the accumulated confirmation files (reorganize into - `year/month`, rename to `YYYY-MM-DD_TICKER_BUY|SELL.txt`). `ConfineWorkingDirectory` re-anchors - every command to the vault and a `ShellPolicy` deny-list pre-filters obviously destructive - commands. Exposed as the `run_shell` tool, which prompts for approval before each command runs. - (The deny-list is a UX guardrail, not a security boundary — for hard isolation use a - `DockerShellExecutor`.) + `year/month`, rename to `YYYY-MM-DD_TICKER_BUY|SELL.txt`). By default the executor moves + every command back to the vault before it runs and a `ShellPolicy` deny-list pre-filters obviously + destructive commands. Exposed as the `run_shell` tool, which prompts for approval before each + command runs. (Neither the working directory nor the deny-list is a security boundary: a command + can still reach files outside the vault. For hard isolation use a `DockerShellExecutor`.) - **CodeAct** — a `HyperlightCodeActProvider` gives the agent a sandboxed Python interpreter to crunch portfolio numbers by writing and running code. It runs on Hyperlight (a micro-VM), so it requires hardware virtualization. The guest module path is resolved automatically from the diff --git a/dotnet/samples/02-agents/Harness/BuildYourOwnClaw/Claw_Step04_ProductionReady/ClawAgent/ClawAgentFactory.cs b/dotnet/samples/02-agents/Harness/BuildYourOwnClaw/Claw_Step04_ProductionReady/ClawAgent/ClawAgentFactory.cs index 69e766e14a8..3ee24272723 100644 --- a/dotnet/samples/02-agents/Harness/BuildYourOwnClaw/Claw_Step04_ProductionReady/ClawAgent/ClawAgentFactory.cs +++ b/dotnet/samples/02-agents/Harness/BuildYourOwnClaw/Claw_Step04_ProductionReady/ClawAgent/ClawAgentFactory.cs @@ -145,15 +145,15 @@ public static async Task CreateAsync(ClawAgentFactoryOptions? op AgentSkillsProvider skillsProvider = skillsBuilder.Build(); AIAgent researchAgent = ResearchAgent.Create(chatClient); - // Shell access is a powerful capability. It is confined to the local vault directory with a - // deny-list here, but on shared/hosted deployments it is disabled entirely (see hosted host). + // Shell access is a powerful capability. Commands start in the local vault directory and a + // deny-list filters obvious mistakes, but neither stops a command from reaching other files; + // approval is the actual check. On shared/hosted deployments it is disabled entirely (see hosted host). LocalShellExecutor? shell = null; if (options.EnableShell) { shell = new LocalShellExecutor(new LocalShellExecutorOptions { WorkingDirectory = vaultDir, - ConfineWorkingDirectory = true, Policy = new ShellPolicy(denyList: [ @"\brm\s+-rf\b", @@ -164,7 +164,7 @@ public static async Task CreateAsync(ClawAgentFactoryOptions? op ]), Timeout = TimeSpan.FromSeconds(15), }); - log("Shell enabled (confined to the confirmations vault). "); + log("Shell enabled (commands start in the confirmations vault and require approval). "); } else { diff --git a/dotnet/samples/02-agents/Harness/BuildYourOwnClaw/Claw_Step04_ProductionReady/ClawAgent/README.md b/dotnet/samples/02-agents/Harness/BuildYourOwnClaw/Claw_Step04_ProductionReady/ClawAgent/README.md index 3a04dec0291..53b716591fc 100644 --- a/dotnet/samples/02-agents/Harness/BuildYourOwnClaw/Claw_Step04_ProductionReady/ClawAgent/README.md +++ b/dotnet/samples/02-agents/Harness/BuildYourOwnClaw/Claw_Step04_ProductionReady/ClawAgent/README.md @@ -2,6 +2,6 @@ Shared class library for the production-ready personal finance claw. -`ClawAgentFactory.CreateAsync(...)` returns a `ClawAgentBuild` containing the fully configured `AIAgent` plus disposable resources. It preserves the Step 03 capabilities: Foundry Responses `IChatClient`, local file skills, optional Foundry Toolbox MCP skills, background research agent, confined `LocalShellExecutor`, Hyperlight CodeAct, file access, approvals, agent modes, stock tools, and trading tools. +`ClawAgentFactory.CreateAsync(...)` returns a `ClawAgentBuild` containing the fully configured `AIAgent` plus disposable resources. It preserves the Step 03 capabilities: Foundry Responses `IChatClient`, local file skills, optional Foundry Toolbox MCP skills, background research agent, approval-gated `LocalShellExecutor`, Hyperlight CodeAct, file access, approvals, agent modes, stock tools, and trading tools. Purview is opt-in via `PURVIEW_CLIENT_APP_ID`; when unset, the chat client is not wrapped. Telemetry is always enabled through `HarnessAgentOptions.OpenTelemetrySourceName`. diff --git a/dotnet/samples/02-agents/Harness/README.md b/dotnet/samples/02-agents/Harness/README.md index 3db5e944d2c..26748d922f3 100644 --- a/dotnet/samples/02-agents/Harness/README.md +++ b/dotnet/samples/02-agents/Harness/README.md @@ -32,7 +32,7 @@ Samples accompanying the [*Build your own agent harness or claw with Microsoft A | --- | --- | | [Claw_Step01_MeetYourClaw](./BuildYourOwnClaw/Claw_Step01_MeetYourClaw/README.md) | Post 1 — a minimal HarnessAgent with a custom `get_stock_price` tool, web search, and planning | | [Claw_Step02_WorkingWithData](./BuildYourOwnClaw/Claw_Step02_WorkingWithData/README.md) | Post 2 — file access, approvals, and durable memory (file memory plus optional Foundry memory) | -| [Claw_Step03_ScalingCapabilities](./BuildYourOwnClaw/Claw_Step03_ScalingCapabilities/README.md) | Post 3 — scaling the claw with skills (plus optional Foundry skills), a confined shell, CodeAct, and background agents | +| [Claw_Step03_ScalingCapabilities](./BuildYourOwnClaw/Claw_Step03_ScalingCapabilities/README.md) | Post 3 — scaling the claw with skills (plus optional Foundry skills), an approval-gated local shell, CodeAct, and background agents | | [Claw_Step04_ProductionReady](./BuildYourOwnClaw/Claw_Step04_ProductionReady/README.md) | Post 4 — production-ready shared claw library with observability, opt-in Purview governance, Foundry hosted deployment, and evals | ## Foundry hosted Harness sample diff --git a/dotnet/src/Microsoft.Agents.AI.Tools.Shell/DockerShellExecutor.cs b/dotnet/src/Microsoft.Agents.AI.Tools.Shell/DockerShellExecutor.cs index 40f12c57309..9812e08d4b0 100644 --- a/dotnet/src/Microsoft.Agents.AI.Tools.Shell/DockerShellExecutor.cs +++ b/dotnet/src/Microsoft.Agents.AI.Tools.Shell/DockerShellExecutor.cs @@ -187,7 +187,7 @@ public override async Task InitializeAsync(CancellationToken cancellationToken = this._session = new ShellSession( inner, workingDirectory: null, // workdir is set on the container itself - confineWorkingDirectory: false, + resetWorkingDirectoryEachCall: false, environment: null, cleanEnvironment: false, maxOutputBytes: this._maxOutputBytes); diff --git a/dotnet/src/Microsoft.Agents.AI.Tools.Shell/LocalShellExecutor.cs b/dotnet/src/Microsoft.Agents.AI.Tools.Shell/LocalShellExecutor.cs index 857a610b622..2b4ad9ee699 100644 --- a/dotnet/src/Microsoft.Agents.AI.Tools.Shell/LocalShellExecutor.cs +++ b/dotnet/src/Microsoft.Agents.AI.Tools.Shell/LocalShellExecutor.cs @@ -65,7 +65,7 @@ public sealed class LocalShellExecutor : ShellExecutor private readonly TimeSpan? _timeout; private readonly int _maxOutputBytes; private readonly string? _workingDirectory; - private readonly bool _confineWorkingDirectory; + private readonly bool _resetWorkingDirectoryEachCall; private readonly IReadOnlyDictionary? _environment; private readonly bool _cleanEnvironment; private readonly bool _acknowledgeUnsafe; @@ -109,7 +109,7 @@ public LocalShellExecutor(LocalShellExecutorOptions options) this._timeout = options.Timeout; this._maxOutputBytes = options.MaxOutputBytes; this._workingDirectory = options.WorkingDirectory; - this._confineWorkingDirectory = options.ConfineWorkingDirectory; + this._resetWorkingDirectoryEachCall = !options.DisableWorkingDirectoryResetOnEachCall; this._environment = options.Environment; this._cleanEnvironment = options.CleanEnvironment; this._acknowledgeUnsafe = options.AcknowledgeUnsafe; @@ -162,7 +162,7 @@ private async Task RunPersistentAsync(string command, CancellationT this._session ??= new ShellSession( this._shell, this._workingDirectory, - this._confineWorkingDirectory, + this._resetWorkingDirectoryEachCall, this._environment, this._cleanEnvironment, this._maxOutputBytes); @@ -186,7 +186,7 @@ public override Task InitializeAsync(CancellationToken cancellationToken = defau this._session ??= new ShellSession( this._shell, this._workingDirectory, - this._confineWorkingDirectory, + this._resetWorkingDirectoryEachCall, this._environment, this._cleanEnvironment, this._maxOutputBytes); diff --git a/dotnet/src/Microsoft.Agents.AI.Tools.Shell/LocalShellExecutorOptions.cs b/dotnet/src/Microsoft.Agents.AI.Tools.Shell/LocalShellExecutorOptions.cs index 8e6c09d13a1..77079995f74 100644 --- a/dotnet/src/Microsoft.Agents.AI.Tools.Shell/LocalShellExecutorOptions.cs +++ b/dotnet/src/Microsoft.Agents.AI.Tools.Shell/LocalShellExecutorOptions.cs @@ -48,18 +48,34 @@ public sealed class LocalShellExecutorOptions /// /// Working directory for the spawned shell. Defaults to the current - /// process directory. Required when - /// is . + /// process directory. This is only where commands start; it does not + /// limit which files a command can reach. + /// In persistent mode, each command starts here again unless + /// is set. /// public string? WorkingDirectory { get; set; } /// - /// When (the default), every command in + /// When (the default), every command in /// persistent mode is prefixed with a cd back into - /// so a wandering cd in one call - /// doesn't leak to the next. + /// so a cd in one call + /// doesn't carry over to the next. Set to to let + /// a cd carry over to later calls. The reset only happens when + /// is set. This option has no effect in + /// stateless mode, where every command already starts in + /// . /// - public bool ConfineWorkingDirectory { get; set; } = true; + /// + /// The reset does not restrict file access. It only sets where a command + /// starts. A command can still change directory or use absolute paths + /// within the same call: cd /tmp && rm -rf . touches + /// /tmp, and cat /etc/passwd reads a file outside + /// . only filters + /// command text; it does not restrict file access either. To limit what + /// commands can reach, use an executor with separately enforced isolation + /// and restricted permissions, such as . + /// + public bool DisableWorkingDirectoryResetOnEachCall { get; set; } /// /// Extra environment variables. Pass a value to diff --git a/dotnet/src/Microsoft.Agents.AI.Tools.Shell/ShellSession.cs b/dotnet/src/Microsoft.Agents.AI.Tools.Shell/ShellSession.cs index 66e586c76af..283950a6fb3 100644 --- a/dotnet/src/Microsoft.Agents.AI.Tools.Shell/ShellSession.cs +++ b/dotnet/src/Microsoft.Agents.AI.Tools.Shell/ShellSession.cs @@ -69,7 +69,7 @@ internal sealed class ShellSession : IAsyncDisposable private readonly ResolvedShell _shell; private readonly string? _workingDirectory; - private readonly bool _confineWorkingDirectory; + private readonly bool _resetWorkingDirectoryEachCall; private readonly IReadOnlyDictionary? _environment; private readonly bool _cleanEnvironment; private readonly int _maxOutputBytes; @@ -95,14 +95,14 @@ internal sealed class ShellSession : IAsyncDisposable public ShellSession( ResolvedShell shell, string? workingDirectory, - bool confineWorkingDirectory, + bool resetWorkingDirectoryEachCall, IReadOnlyDictionary? environment, bool cleanEnvironment, int maxOutputBytes) { this._shell = shell; this._workingDirectory = workingDirectory; - this._confineWorkingDirectory = confineWorkingDirectory; + this._resetWorkingDirectoryEachCall = resetWorkingDirectoryEachCall; this._environment = environment; this._cleanEnvironment = cleanEnvironment; this._maxOutputBytes = maxOutputBytes; @@ -563,10 +563,11 @@ private static int ParseRc(byte[] tail, int newlineIdx) private string BuildScript(string command, string sentinel) { - // Idempotent re-anchor: in confined mode every command is prefixed - // with a `cd` back to the configured workdir so a `cd` inside one - // command doesn't leak to the next. - var effective = this.MaybeReanchor(command); + // Idempotent reset: when enabled, every command is prefixed with a + // `cd` back to the configured workdir so a `cd` inside one command + // doesn't leak to the next. This only sets the starting directory; + // it does not restrict what the command can reach. + var effective = this.MaybeResetWorkingDirectory(command); if (this._shell.Kind == ShellKind.PowerShell) { @@ -619,9 +620,9 @@ private string BuildScript(string command, string sentinel) $"printf '\\n{sentinel}_%s\\n' \"$__af_rc\"\n"; } - private string MaybeReanchor(string command) + private string MaybeResetWorkingDirectory(string command) { - if (!this._confineWorkingDirectory || string.IsNullOrEmpty(this._workingDirectory)) + if (!this._resetWorkingDirectoryEachCall || string.IsNullOrEmpty(this._workingDirectory)) { return command; } diff --git a/dotnet/tests/Microsoft.Agents.AI.Tools.Shell.UnitTests/LocalShellExecutorTests.cs b/dotnet/tests/Microsoft.Agents.AI.Tools.Shell.UnitTests/LocalShellExecutorTests.cs index 4e13f13c09a..caf8391f924 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Tools.Shell.UnitTests/LocalShellExecutorTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Tools.Shell.UnitTests/LocalShellExecutorTests.cs @@ -416,10 +416,10 @@ public void Ctor_RejectsBothShellAndShellArgv() } [Fact] - public async Task Persistent_ConfineWorkdir_ReanchorsAfterCdAwayAsync() + public async Task Persistent_ByDefault_StartsInWorkingDirectoryAfterCdAwayAsync() { var rootDir = Path.GetTempPath(); - var subDir = Path.Combine(rootDir, "af-shell-confine-" + Guid.NewGuid().ToString("N")[..8]); + var subDir = Path.Join(rootDir, "af-shell-reset-" + Guid.NewGuid().ToString("N")[..8]); Directory.CreateDirectory(subDir); try { @@ -427,7 +427,6 @@ public async Task Persistent_ConfineWorkdir_ReanchorsAfterCdAwayAsync() { Mode = ShellMode.Persistent, WorkingDirectory = rootDir, - ConfineWorkingDirectory = true, Timeout = TimeSpan.FromSeconds(20), }); @@ -437,7 +436,7 @@ public async Task Persistent_ConfineWorkdir_ReanchorsAfterCdAwayAsync() : $"cd \"{subDir}\""; _ = await shell.RunAsync(cd); - // Second call: pwd. With confinement we should be re-anchored to rootDir. + // Second call: pwd. With the reset enabled we should start in rootDir again. var pwdCmd = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "(Get-Location).Path" : "pwd"; var result = await shell.RunAsync(pwdCmd); Assert.Equal(0, result.ExitCode); @@ -452,10 +451,51 @@ public async Task Persistent_ConfineWorkdir_ReanchorsAfterCdAwayAsync() } [Fact] - public async Task Persistent_ConfineDisabled_AllowsCdToLeakAsync() + public async Task Persistent_WorkingDirectoryReset_DoesNotRestrictFileAccessAsync() + { + // Arrange + var rootDir = Path.Join(Path.GetTempPath(), "af-shell-access-" + Guid.NewGuid().ToString("N")[..8]); + var workDir = Path.Join(rootDir, "work"); + Directory.CreateDirectory(workDir); + var outsideFile = Path.Join(rootDir, "outside.txt"); + File.WriteAllText(outsideFile, "outside-content"); + try + { + await using var shell = new LocalShellExecutor(new() + { + Mode = ShellMode.Persistent, + WorkingDirectory = workDir, + Timeout = TimeSpan.FromSeconds(20), + }); + var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); + var readAfterCd = isWindows + ? "Set-Location ..; Get-Content -Raw outside.txt" + : "cd .. && cat outside.txt"; + var readByPath = isWindows + ? $"Get-Content -Raw -LiteralPath '{outsideFile}'" + : $"cat '{outsideFile}'"; + + // Act + var afterCd = await shell.RunAsync(readAfterCd); + var byPath = await shell.RunAsync(readByPath); + + // Assert: the option only sets where a command starts; it does not block access outside it. + Assert.Equal(0, afterCd.ExitCode); + Assert.Contains("outside-content", afterCd.Stdout, StringComparison.Ordinal); + Assert.Equal(0, byPath.ExitCode); + Assert.Contains("outside-content", byPath.Stdout, StringComparison.Ordinal); + } + finally + { + try { Directory.Delete(rootDir, recursive: true); } catch (IOException) { } catch (UnauthorizedAccessException) { } + } + } + + [Fact] + public async Task Persistent_DisableWorkingDirectoryResetOnEachCall_AllowsCdToLeakAsync() { var rootDir = Path.GetTempPath(); - var subDir = Path.Combine(rootDir, "af-shell-noconfine-" + Guid.NewGuid().ToString("N")[..8]); + var subDir = Path.Join(rootDir, "af-shell-noreset-" + Guid.NewGuid().ToString("N")[..8]); Directory.CreateDirectory(subDir); try { @@ -463,7 +503,7 @@ public async Task Persistent_ConfineDisabled_AllowsCdToLeakAsync() { Mode = ShellMode.Persistent, WorkingDirectory = rootDir, - ConfineWorkingDirectory = false, + DisableWorkingDirectoryResetOnEachCall = true, Timeout = TimeSpan.FromSeconds(20), }); diff --git a/python/packages/tools/README.md b/python/packages/tools/README.md index 8d9154fd0af..d0057182fb4 100644 --- a/python/packages/tools/README.md +++ b/python/packages/tools/README.md @@ -81,6 +81,15 @@ Defenses (in priority order): neither approval nor command filters isolate the shell. See `tests/test_security.py` for the documented residual risk surface. +`workdir` and the per-call working-directory reset are **not** defenses. +`workdir` is only where commands start. By default, each persistent-mode +command is moved back to `workdir` before it runs, so a `cd` in one call does +not carry over to the next; pass `disable_workdir_reset_on_each_call=True` to +turn this off. The reset only happens when `workdir` is set explicitly. +Neither restricts file access: a +command can still change directory or use absolute paths to read and write +anywhere the agent process can. + Command-text filtering with `ShellPolicy` and required human approval: > [!WARNING] diff --git a/python/packages/tools/agent_framework_tools/shell/_tool.py b/python/packages/tools/agent_framework_tools/shell/_tool.py index 3555b741fcb..362adebd4d8 100644 --- a/python/packages/tools/agent_framework_tools/shell/_tool.py +++ b/python/packages/tools/agent_framework_tools/shell/_tool.py @@ -111,17 +111,26 @@ class LocalShellTool: current directory is never searched. Pass an absolute path to select a specific executable. workdir: Working directory for commands. Defaults to the current - working directory. In persistent mode, each command is - re-anchored to this directory when ``confine_workdir=True`` — - see that argument for the exact semantics and caveats. - confine_workdir: When ``True`` (default), each command in persistent - mode is prefixed with a ``cd`` back into ``workdir`` so - ``cd``-wandering in one call does not leak to the next. This is - a **re-anchor**, not a hard confinement — a command that does - ``cd /tmp && rm -rf .`` in one call can still touch ``/tmp``. - :class:`ShellPolicy` only filters command text; it does not - restrict file access. Use an executor with separately enforced - isolation and restricted permissions to limit access. + working directory. This is only where commands start; it does + not limit which files a command can reach. In persistent mode, + each command starts here again unless + ``disable_workdir_reset_on_each_call=True`` — see that argument. + disable_workdir_reset_on_each_call: When ``False`` (default), each + command in persistent mode is prefixed with a ``cd`` back into + ``workdir``, so a ``cd`` in one call does not carry over to the + next. Set to ``True`` to let a ``cd`` carry over to later calls. + The reset only happens when ``workdir`` is set explicitly. This + argument has no effect in stateless mode, where every command + already starts in ``workdir``. + + **The reset does not restrict file access.** It only sets where a + command starts. A command can still change directory or use + absolute paths within the same call: ``cd /tmp && rm -rf .`` + touches ``/tmp``, and ``cat /etc/passwd`` reads a file outside + ``workdir``. :class:`ShellPolicy` only filters command text; it + does not restrict file access either. To limit what commands can + reach, use an executor with separately enforced isolation and + restricted permissions, such as :class:`DockerShellTool`. env: Seed environment. In stateless mode this replaces the child's environment unless ``clean_env=False``. In persistent mode the variables are exported before the session is used. @@ -171,7 +180,7 @@ def __init__( mode: ShellMode = "persistent", shell: str | Sequence[str] | None = None, workdir: str | os.PathLike[str] | None = None, - confine_workdir: bool = True, + disable_workdir_reset_on_each_call: bool = False, env: Mapping[str, str] | None = None, clean_env: bool = False, policy: ShellPolicy | None = None, @@ -198,7 +207,7 @@ def __init__( self._mode: ShellMode = mode self._shell_override = shell self._workdir: str | None = os.fspath(workdir) if workdir is not None else None - self._confine_workdir = confine_workdir + self._reset_workdir_each_call = not disable_workdir_reset_on_each_call self._policy = policy or ShellPolicy() self._timeout = timeout self._max_stdout_bytes = max_stdout_bytes @@ -298,7 +307,7 @@ async def run(self, command: str, *, timeout: float | None = None) -> ShellResul await self.start() if self._session is None: raise RuntimeError("LocalShellTool session failed to start") - effective = self._maybe_reanchor(command) + effective = self._maybe_reset_workdir(command) return await self._session.run(effective, timeout=effective_timeout) return await run_stateless( @@ -360,12 +369,13 @@ async def _run_shell(command: str) -> str: # ------------------------------------------------------------------ helpers - def _maybe_reanchor(self, command: str) -> str: - """Prefix ``cd`` when confinement is enabled and workdir is set.""" - if not self._confine_workdir or self._workdir is None: + def _maybe_reset_workdir(self, command: str) -> str: + """Prefix ``cd`` unless the reset is disabled or workdir is not set.""" + if not self._reset_workdir_each_call or self._workdir is None: return command # Idempotent prefix: cd back before each command so a `cd` in one - # call does not leak workdir state to the next. + # call does not leak workdir state to the next. This only sets the + # starting directory; it does not restrict what the command can reach. if self._interactive_argv and is_powershell(self._interactive_argv): return f"Set-Location -LiteralPath {_quote_powershell(self._workdir)}\n{command}" return f"cd -- {_quote_posix(self._workdir)}\n{command}" diff --git a/python/packages/tools/tests/test_local_shell_tool.py b/python/packages/tools/tests/test_local_shell_tool.py index 6bd213a8f64..edfe8e47ca9 100644 --- a/python/packages/tools/tests/test_local_shell_tool.py +++ b/python/packages/tools/tests/test_local_shell_tool.py @@ -638,7 +638,7 @@ async def test_local_shell_tool_as_function_returns_policy_errors() -> None: assert function.description == "custom shell" -def test_local_shell_tool_reanchors_powershell_paths() -> None: +def test_local_shell_tool_resets_workdir_with_powershell_paths() -> None: tool = LocalShellTool( mode="persistent", shell=[r"C:\Program Files\PowerShell\7\pwsh.exe"] if sys.platform == "win32" else ["/usr/bin/pwsh"], @@ -647,7 +647,7 @@ def test_local_shell_tool_reanchors_powershell_paths() -> None: acknowledge_unsafe=True, ) - assert tool._maybe_reanchor("Get-ChildItem").startswith("Set-Location -LiteralPath 'C:\\repo'") + assert tool._maybe_reset_workdir("Get-ChildItem").startswith("Set-Location -LiteralPath 'C:\\repo'") def test_popen_kwargs_for_group_covers_windows_branch(monkeypatch: pytest.MonkeyPatch) -> None: @@ -715,7 +715,7 @@ async def test_persistent_preserves_cwd_and_exports_across_calls(tmp_path: os.Pa approval_mode="never_require", acknowledge_unsafe=True, workdir=str(tmp_path), - confine_workdir=False, + disable_workdir_reset_on_each_call=True, ) as tool: await tool.run("export AGENT_FRAMEWORK_TEST_MARKER=xyz") result = await tool.run("echo $AGENT_FRAMEWORK_TEST_MARKER") @@ -824,7 +824,7 @@ async def test_persistent_preserves_state_powershell(tmp_path: os.PathLike[str]) approval_mode="never_require", acknowledge_unsafe=True, workdir=str(tmp_path), - confine_workdir=False, + disable_workdir_reset_on_each_call=True, ) as tool: await tool.run("$env:AGENT_FRAMEWORK_TEST_MARKER = 'xyz'") result = await tool.run("Write-Output $env:AGENT_FRAMEWORK_TEST_MARKER") @@ -962,10 +962,10 @@ async def test_variable_shell_approval_cannot_be_replayed_on_later_turn_or_sessi assert create_process.await_args.args == (_TEST_SHELL, "-c", _APPROVED_COMMAND) -@pytest.mark.skipif(sys.platform == "win32", reason="POSIX persistent reanchor test") -async def test_persistent_confines_workdir_by_default(tmp_path: os.PathLike[str]) -> None: - """With the default ``confine_workdir=True``, a ``cd`` in one call - must not leak into the next: each command is reanchored to ``workdir``.""" +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX persistent workdir reset test") +async def test_persistent_resets_workdir_each_call_by_default(tmp_path: os.PathLike[str]) -> None: + """By default (``disable_workdir_reset_on_each_call=False``), a ``cd`` in one call + must not leak into the next: each command starts in ``workdir`` again.""" subdir = os.path.join(str(tmp_path), "sub") os.mkdir(subdir) async with LocalShellTool( @@ -979,6 +979,32 @@ async def test_persistent_confines_workdir_by_default(tmp_path: os.PathLike[str] assert os.path.realpath(pwd.stdout.strip()) == os.path.realpath(str(tmp_path)) +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX persistent workdir reset test") +async def test_persistent_workdir_reset_does_not_restrict_file_access(tmp_path: Path) -> None: + """The per-call workdir reset only sets where a command starts. A single + command can still leave ``workdir`` and read files outside it; only the + next call starts back in ``workdir``.""" + workdir = tmp_path / "work" + workdir.mkdir() + outside = tmp_path / "outside.txt" + outside.write_text("outside-content", encoding="utf-8") + async with LocalShellTool( + mode="persistent", + approval_mode="never_require", + acknowledge_unsafe=True, + workdir=workdir, + ) as tool: + moved = await tool.run("cd .. && pwd && cat outside.txt") + by_path = await tool.run(f"cat '{outside}'") + pwd = await tool.run("pwd") + + moved_lines = moved.stdout.splitlines() + assert os.path.realpath(moved_lines[0]) == os.path.realpath(str(tmp_path)) + assert moved_lines[1] == "outside-content" + assert by_path.stdout.strip() == "outside-content" + assert os.path.realpath(pwd.stdout.strip()) == os.path.realpath(workdir) + + @pytest.mark.parametrize( ("failure", "max_stderr_bytes"), [("timeout", 128), ("unrecoverable_timeout", 128), ("overflow", 1), ("overflow", 8192)], @@ -1249,9 +1275,9 @@ async def delayed_create_process(*args: Any, **kwargs: Any) -> asyncio.subproces await asyncio.gather(*tasks, return_exceptions=True) -@pytest.mark.skipif(sys.platform != "win32", reason="PowerShell persistent reanchor test") -async def test_persistent_confines_workdir_by_default_powershell(tmp_path: os.PathLike[str]) -> None: - """PowerShell counterpart of the POSIX confinement check.""" +@pytest.mark.skipif(sys.platform != "win32", reason="PowerShell persistent workdir reset test") +async def test_persistent_resets_workdir_each_call_by_default_powershell(tmp_path: os.PathLike[str]) -> None: + """PowerShell counterpart of the POSIX workdir reset check.""" subdir = os.path.join(str(tmp_path), "sub") os.mkdir(subdir) async with LocalShellTool( diff --git a/python/packages/tools/tests/test_shell_truncate_and_quote.py b/python/packages/tools/tests/test_shell_truncate_and_quote.py index 526de6710f0..74a1a9f53d4 100644 --- a/python/packages/tools/tests/test_shell_truncate_and_quote.py +++ b/python/packages/tools/tests/test_shell_truncate_and_quote.py @@ -1,6 +1,6 @@ # Copyright (c) Microsoft. All rights reserved. -"""Unit tests for the head/tail truncation helper and the reanchor quoter.""" +"""Unit tests for the head/tail truncation helper and the workdir-reset quoter.""" from __future__ import annotations diff --git a/python/samples/02-agents/harness/build_your_own_claw/README.md b/python/samples/02-agents/harness/build_your_own_claw/README.md index 69a4f121373..ff50bfc1823 100644 --- a/python/samples/02-agents/harness/build_your_own_claw/README.md +++ b/python/samples/02-agents/harness/build_your_own_claw/README.md @@ -137,11 +137,13 @@ Makes the assistant *more capable* along four axes. `FileSkillsSource(..., script_runner=subprocess_script_runner)` so the skills' Python scripts can run. Optionally folds in centrally-managed **Foundry skills** served from a Foundry Toolbox MCP endpoint via `MCPSkillsSource` (opt-in; see below). -- **Shell** — a `LocalShellTool` confined to the trade-confirmation vault +- **Shell** — a `LocalShellTool` that starts each command in the trade-confirmation vault (`working/confirmations/`) lets the agent tidy the accumulated confirmation files (reorganize into - `year/month`, rename to `YYYY-MM-DD_TICKER_BUY|SELL.txt`). Guarded by a `ShellPolicy` deny-list - **and** a confined working directory; left at the default - `approval_mode="always_require"` so each command is surfaced for approval. + `year/month`, rename to `YYYY-MM-DD_TICKER_BUY|SELL.txt`). By default the tool moves every + command back to the vault before it runs, and a `ShellPolicy` deny-list pre-filters obviously + destructive commands. Neither is a security boundary: a command can still reach files outside + the vault. The shell is left at the default `approval_mode="always_require"` so each command is + surfaced for approval, which is the actual check. For hard isolation use `DockerShellTool`. - **CodeAct** — a `MontyCodeActProvider` gives the agent a sandboxed, cross-platform Python interpreter to crunch portfolio numbers by writing and running code. - **Background agents** — a lean, web-search-only `TickerResearchAgent` is registered via diff --git a/python/samples/02-agents/harness/build_your_own_claw/claw_step03_scaling_capabilities.py b/python/samples/02-agents/harness/build_your_own_claw/claw_step03_scaling_capabilities.py index 0a66bd4ca69..c2f0efe824e 100644 --- a/python/samples/02-agents/harness/build_your_own_claw/claw_step03_scaling_capabilities.py +++ b/python/samples/02-agents/harness/build_your_own_claw/claw_step03_scaling_capabilities.py @@ -26,9 +26,9 @@ files the agent loads on demand. Optionally fold in centrally-managed Foundry skills served from a Foundry Toolbox MCP endpoint (opt-in via FOUNDRY_TOOLBOX_MCP_SERVER_URL). -2. Shell — a sandboxed shell, confined to the trade-confirmation vault, that the agent uses - to reorganize the accumulated confirmation files (year/month, rename, archive). - Guarded by an allow/deny-list policy and a confined working directory. +2. Shell — a local shell that starts each command in the trade-confirmation vault, which the + agent uses to reorganize the accumulated confirmation files (year/month, rename, + archive). Every command needs approval; the shell is not sandboxed. 3. CodeAct — the agent writes and runs Python to crunch portfolio numbers, using the cross-platform Monty interpreter. 4. Background agents — fan out a per-ticker research sub-agent so several tickers are researched @@ -258,17 +258,17 @@ def _build_research_agent(client: FoundryChatClient) -> Any: # def _build_shell() -> LocalShellTool: - """A sandboxed shell, confined to the trade-confirmation vault. + """A local shell that starts each command in the trade-confirmation vault. - ``confine_workdir`` re-anchors every command to the vault, and the deny-list pre-filters - obviously destructive command shapes. (Patterns are a UX guardrail, not a security boundary — - for hard isolation use DockerShellTool.) Left at the default ``approval_mode="always_require"`` - so each command is surfaced for approval. + By default the tool moves every command back to the vault before it runs, and the + deny-list pre-filters obviously destructive command shapes. Neither is a security boundary: + a command can still reach files outside the vault (for example with ``cd ..`` or an absolute + path). Left at the default ``approval_mode="always_require"`` so each command is surfaced for + approval, which is the actual check. For hard isolation use DockerShellTool. """ return LocalShellTool( mode="persistent", workdir=str(_VAULT_DIR), - confine_workdir=True, policy=ShellPolicy( denylist=[ r"\brm\s+-rf\b", @@ -310,7 +310,7 @@ async def main() -> None: # # Turn the chat client into a harness agent. On top of Post 2's file access and approvals we # add the four "scaling" capabilities: skills (our own provider), background agents, a - # confined shell, and optional CodeAct. Read-only file tools are auto-approved so reading the + # an approval-gated shell, and optional CodeAct. Read-only file tools are auto-approved so reading the # portfolio is frictionless while writes, trades, and shell commands still prompt. agent = create_harness_agent( client=client, diff --git a/python/samples/02-agents/harness/build_your_own_claw/claw_step04_production_ready/agent.py b/python/samples/02-agents/harness/build_your_own_claw/claw_step04_production_ready/agent.py index e05a581c8c7..d6f9b440f27 100644 --- a/python/samples/02-agents/harness/build_your_own_claw/claw_step04_production_ready/agent.py +++ b/python/samples/02-agents/harness/build_your_own_claw/claw_step04_production_ready/agent.py @@ -249,11 +249,15 @@ def _build_research_agent(client: FoundryChatClient) -> Any: # def _build_shell() -> LocalShellTool: - """Build a sandboxed shell confined to the trade-confirmation vault.""" + """Build a local shell that starts each command in the trade-confirmation vault. + + The shell is not sandboxed: a command can still reach files outside the vault (for example + with ``cd ..`` or an absolute path). Each command needs approval, which is the actual check. + For hard isolation use DockerShellTool. + """ return LocalShellTool( mode="persistent", workdir=str(_VAULT_DIR), - confine_workdir=True, policy=ShellPolicy( denylist=[ r"\brm\s+-rf\b", @@ -359,7 +363,7 @@ async def build_claw_agent( # outside the deployed package on a hosted container, where shell is off. _VAULT_DIR.mkdir(parents=True, exist_ok=True) shell = _build_shell() - logger.info("Shell enabled (confined to the confirmations vault).") + logger.info("Shell enabled (commands start in the confirmations vault and require approval).") else: shell = None logger.info("Shell disabled.") diff --git a/python/samples/02-agents/providers/openai/client_with_local_shell.py b/python/samples/02-agents/providers/openai/client_with_local_shell.py index ab850711c12..c421412bc5a 100644 --- a/python/samples/02-agents/providers/openai/client_with_local_shell.py +++ b/python/samples/02-agents/providers/openai/client_with_local_shell.py @@ -16,7 +16,8 @@ This sample uses ``LocalShellTool`` from ``agent-framework-tools`` — the framework-supplied cross-OS shell executor with safe defaults (approval -required, timeout, output truncation, workdir confinement). Operators +required, timeout, output truncation). It runs commands directly on the +host and does not restrict which files a command can reach. Operators can additionally supply a ``ShellPolicy`` with allow/deny patterns as a UX pre-filter; the tool ships with no default deny patterns. diff --git a/python/samples/02-agents/tools/local_shell_with_environment_provider.py b/python/samples/02-agents/tools/local_shell_with_environment_provider.py index 9c47ee65ec1..6376762386a 100644 --- a/python/samples/02-agents/tools/local_shell_with_environment_provider.py +++ b/python/samples/02-agents/tools/local_shell_with_environment_provider.py @@ -82,7 +82,7 @@ async def main() -> None: print("\n=== persistent mode ===") async with LocalShellTool( mode="persistent", - confine_workdir=False, + disable_workdir_reset_on_each_call=True, approval_mode="never_require", acknowledge_unsafe=True, ) as shell: