From e442662b6b46129303d1717668526c91a50ae91c Mon Sep 17 00:00:00 2001 From: westey <164392973+westey-m@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:22:13 +0000 Subject: [PATCH 1/4] Clarify working dir reset characteristics --- .../Program.cs | 20 ++++--- .../Claw_Step03_ScalingCapabilities/README.md | 12 ++-- .../ClawAgent/ClawAgentFactory.cs | 9 +-- .../ClawAgent/README.md | 2 +- dotnet/samples/02-agents/Harness/README.md | 2 +- .../DockerShellExecutor.cs | 2 +- .../LocalShellExecutor.cs | 8 +-- .../LocalShellExecutorOptions.cs | 23 ++++++-- .../ShellSession.cs | 19 ++++--- .../LocalShellExecutorTests.cs | 55 ++++++++++++++++--- python/packages/tools/README.md | 7 +++ .../agent_framework_tools/shell/_tool.py | 44 +++++++++------ .../tools/tests/test_local_shell_tool.py | 54 ++++++++++++++---- .../tests/test_shell_truncate_and_quote.py | 2 +- .../harness/build_your_own_claw/README.md | 10 ++-- .../claw_step03_scaling_capabilities.py | 21 +++---- .../claw_step04_production_ready/agent.py | 11 +++- .../openai/client_with_local_shell.py | 3 +- .../local_shell_with_environment_provider.py | 2 +- 19 files changed, 210 insertions(+), 96 deletions(-) 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..13331c42893 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,15 @@ 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. ResetWorkingDirectoryEachCall +// 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, + ResetWorkingDirectoryEachCall = true, Policy = new ShellPolicy(denyList: [ @"\brm\s+-rf\b", @@ -158,7 +160,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 +190,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..53d6226e383 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`). `ResetWorkingDirectoryEachCall` 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..9200c8b3eff 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,16 @@ 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, + ResetWorkingDirectoryEachCall = true, Policy = new ShellPolicy(denyList: [ @"\brm\s+-rf\b", @@ -164,7 +165,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..1ff0244d9c8 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.ResetWorkingDirectoryEachCall; 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..d2921bca0ca 100644 --- a/dotnet/src/Microsoft.Agents.AI.Tools.Shell/LocalShellExecutorOptions.cs +++ b/dotnet/src/Microsoft.Agents.AI.Tools.Shell/LocalShellExecutorOptions.cs @@ -48,18 +48,31 @@ 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. + /// only has an effect when + /// this is set. /// public string? WorkingDirectory { get; set; } /// /// 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. It has no effect in stateless mode, + /// where every command already starts in . /// - public bool ConfineWorkingDirectory { get; set; } = true; + /// + /// This 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 ResetWorkingDirectoryEachCall { get; set; } = true; /// /// 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..0fd75bd3e5a 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_ResetWorkingDirectoryEachCall_StartsInWorkingDirectoryAfterCdAwayAsync() { var rootDir = Path.GetTempPath(); - var subDir = Path.Combine(rootDir, "af-shell-confine-" + Guid.NewGuid().ToString("N")[..8]); + var subDir = Path.Combine(rootDir, "af-shell-reset-" + Guid.NewGuid().ToString("N")[..8]); Directory.CreateDirectory(subDir); try { @@ -427,7 +427,7 @@ public async Task Persistent_ConfineWorkdir_ReanchorsAfterCdAwayAsync() { Mode = ShellMode.Persistent, WorkingDirectory = rootDir, - ConfineWorkingDirectory = true, + ResetWorkingDirectoryEachCall = true, Timeout = TimeSpan.FromSeconds(20), }); @@ -437,7 +437,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 +452,51 @@ public async Task Persistent_ConfineWorkdir_ReanchorsAfterCdAwayAsync() } [Fact] - public async Task Persistent_ConfineDisabled_AllowsCdToLeakAsync() + public async Task Persistent_ResetWorkingDirectoryEachCall_DoesNotRestrictFileAccessAsync() + { + // Arrange + var rootDir = Path.Combine(Path.GetTempPath(), "af-shell-access-" + Guid.NewGuid().ToString("N")[..8]); + var workDir = Path.Combine(rootDir, "work"); + Directory.CreateDirectory(workDir); + var outsideFile = Path.Combine(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 { } + } + } + + [Fact] + public async Task Persistent_ResetWorkingDirectoryEachCallDisabled_AllowsCdToLeakAsync() { var rootDir = Path.GetTempPath(); - var subDir = Path.Combine(rootDir, "af-shell-noconfine-" + Guid.NewGuid().ToString("N")[..8]); + var subDir = Path.Combine(rootDir, "af-shell-noreset-" + Guid.NewGuid().ToString("N")[..8]); Directory.CreateDirectory(subDir); try { @@ -463,7 +504,7 @@ public async Task Persistent_ConfineDisabled_AllowsCdToLeakAsync() { Mode = ShellMode.Persistent, WorkingDirectory = rootDir, - ConfineWorkingDirectory = false, + ResetWorkingDirectoryEachCall = false, Timeout = TimeSpan.FromSeconds(20), }); diff --git a/python/packages/tools/README.md b/python/packages/tools/README.md index 8d9154fd0af..302e823eb02 100644 --- a/python/packages/tools/README.md +++ b/python/packages/tools/README.md @@ -81,6 +81,13 @@ 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 `reset_workdir_each_call` are **not** defenses. `workdir` is +only where commands start. `reset_workdir_each_call=True` (the default) moves +each persistent-mode command back to `workdir` before it runs, so a `cd` in +one call does not carry over to the next. 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..61e33b672e0 100644 --- a/python/packages/tools/agent_framework_tools/shell/_tool.py +++ b/python/packages/tools/agent_framework_tools/shell/_tool.py @@ -111,17 +111,24 @@ 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 when + ``reset_workdir_each_call=True`` — see that argument. + reset_workdir_each_call: When ``True`` (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. It has + no effect in stateless mode, where every command already starts + in ``workdir``. + + **This 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 +178,7 @@ def __init__( mode: ShellMode = "persistent", shell: str | Sequence[str] | None = None, workdir: str | os.PathLike[str] | None = None, - confine_workdir: bool = True, + reset_workdir_each_call: bool = True, env: Mapping[str, str] | None = None, clean_env: bool = False, policy: ShellPolicy | None = None, @@ -198,7 +205,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 = reset_workdir_each_call self._policy = policy or ShellPolicy() self._timeout = timeout self._max_stdout_bytes = max_stdout_bytes @@ -298,7 +305,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 +367,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`` when ``reset_workdir_each_call`` is enabled and workdir is 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..a8e63234cb8 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, + reset_workdir_each_call=False, ) 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, + reset_workdir_each_call=False, ) 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: + """With the default ``reset_workdir_each_call=True``, 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,38 @@ 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_reset_workdir_each_call_does_not_restrict_file_access(tmp_path: os.PathLike[str]) -> None: + """``reset_workdir_each_call`` 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 = os.path.join(str(tmp_path), "work") + os.mkdir(workdir) + outside = os.path.join(str(tmp_path), "outside.txt") + with open(outside, "w", encoding="utf-8") as f: + f.write("outside-content") + 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.split() + 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) + + +def test_local_shell_tool_rejects_removed_confine_workdir_argument() -> None: + with pytest.raises(TypeError): + LocalShellTool(confine_workdir=True) # type: ignore[call-arg] + + @pytest.mark.parametrize( ("failure", "max_stderr_bytes"), [("timeout", 128), ("unrecoverable_timeout", 128), ("overflow", 1), ("overflow", 8192)], @@ -1249,9 +1281,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..9deb9ab846f 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`). `reset_workdir_each_call` 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..fac30c75e7d 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,18 @@ 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. + ``reset_workdir_each_call`` 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, + reset_workdir_each_call=True, policy=ShellPolicy( denylist=[ r"\brm\s+-rf\b", @@ -310,7 +311,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..9904a99aa57 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,16 @@ 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, + reset_workdir_each_call=True, policy=ShellPolicy( denylist=[ r"\brm\s+-rf\b", @@ -359,7 +364,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..fed78578f16 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, + reset_workdir_each_call=False, approval_mode="never_require", acknowledge_unsafe=True, ) as shell: From 626f0a67eeb9dd22c462539eb919d89c8da9dd70 Mon Sep 17 00:00:00 2001 From: westey <164392973+westey-m@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:55:48 +0000 Subject: [PATCH 2/4] Address PR comments --- .../LocalShellExecutorTests.cs | 12 ++++++------ python/packages/tools/README.md | 3 ++- .../tools/agent_framework_tools/shell/_tool.py | 7 ++++--- .../packages/tools/tests/test_local_shell_tool.py | 15 +++++++-------- 4 files changed, 19 insertions(+), 18 deletions(-) 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 0fd75bd3e5a..1068d03a31a 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Tools.Shell.UnitTests/LocalShellExecutorTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Tools.Shell.UnitTests/LocalShellExecutorTests.cs @@ -419,7 +419,7 @@ public void Ctor_RejectsBothShellAndShellArgv() public async Task Persistent_ResetWorkingDirectoryEachCall_StartsInWorkingDirectoryAfterCdAwayAsync() { var rootDir = Path.GetTempPath(); - var subDir = Path.Combine(rootDir, "af-shell-reset-" + Guid.NewGuid().ToString("N")[..8]); + var subDir = Path.Join(rootDir, "af-shell-reset-" + Guid.NewGuid().ToString("N")[..8]); Directory.CreateDirectory(subDir); try { @@ -455,10 +455,10 @@ public async Task Persistent_ResetWorkingDirectoryEachCall_StartsInWorkingDirect public async Task Persistent_ResetWorkingDirectoryEachCall_DoesNotRestrictFileAccessAsync() { // Arrange - var rootDir = Path.Combine(Path.GetTempPath(), "af-shell-access-" + Guid.NewGuid().ToString("N")[..8]); - var workDir = Path.Combine(rootDir, "work"); + 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.Combine(rootDir, "outside.txt"); + var outsideFile = Path.Join(rootDir, "outside.txt"); File.WriteAllText(outsideFile, "outside-content"); try { @@ -488,7 +488,7 @@ public async Task Persistent_ResetWorkingDirectoryEachCall_DoesNotRestrictFileAc } finally { - try { Directory.Delete(rootDir, recursive: true); } catch { } + try { Directory.Delete(rootDir, recursive: true); } catch (IOException) { } catch (UnauthorizedAccessException) { } } } @@ -496,7 +496,7 @@ public async Task Persistent_ResetWorkingDirectoryEachCall_DoesNotRestrictFileAc public async Task Persistent_ResetWorkingDirectoryEachCallDisabled_AllowsCdToLeakAsync() { var rootDir = Path.GetTempPath(); - var subDir = Path.Combine(rootDir, "af-shell-noreset-" + Guid.NewGuid().ToString("N")[..8]); + var subDir = Path.Join(rootDir, "af-shell-noreset-" + Guid.NewGuid().ToString("N")[..8]); Directory.CreateDirectory(subDir); try { diff --git a/python/packages/tools/README.md b/python/packages/tools/README.md index 302e823eb02..0fda195ad72 100644 --- a/python/packages/tools/README.md +++ b/python/packages/tools/README.md @@ -84,7 +84,8 @@ Defenses (in priority order): `workdir` and `reset_workdir_each_call` are **not** defenses. `workdir` is only where commands start. `reset_workdir_each_call=True` (the default) moves each persistent-mode command back to `workdir` before it runs, so a `cd` in -one call does not carry over to the next. Neither restricts file access: a +one call does not carry over to the next. It only has an effect 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. diff --git a/python/packages/tools/agent_framework_tools/shell/_tool.py b/python/packages/tools/agent_framework_tools/shell/_tool.py index 61e33b672e0..c93e56afaad 100644 --- a/python/packages/tools/agent_framework_tools/shell/_tool.py +++ b/python/packages/tools/agent_framework_tools/shell/_tool.py @@ -117,9 +117,10 @@ class LocalShellTool: ``reset_workdir_each_call=True`` — see that argument. reset_workdir_each_call: When ``True`` (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. It has - no effect in stateless mode, where every command already starts - in ``workdir``. + so a ``cd`` in one call does not carry over to the next. It only + has an effect when ``workdir`` is set explicitly. It has no + effect in stateless mode, where every command already starts in + ``workdir``. **This does not restrict file access.** It only sets where a command starts. A command can still change directory or use diff --git a/python/packages/tools/tests/test_local_shell_tool.py b/python/packages/tools/tests/test_local_shell_tool.py index a8e63234cb8..0c5f871c2f8 100644 --- a/python/packages/tools/tests/test_local_shell_tool.py +++ b/python/packages/tools/tests/test_local_shell_tool.py @@ -980,15 +980,14 @@ async def test_persistent_resets_workdir_each_call_by_default(tmp_path: os.PathL @pytest.mark.skipif(sys.platform == "win32", reason="POSIX persistent workdir reset test") -async def test_persistent_reset_workdir_each_call_does_not_restrict_file_access(tmp_path: os.PathLike[str]) -> None: +async def test_persistent_reset_workdir_each_call_does_not_restrict_file_access(tmp_path: Path) -> None: """``reset_workdir_each_call`` 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 = os.path.join(str(tmp_path), "work") - os.mkdir(workdir) - outside = os.path.join(str(tmp_path), "outside.txt") - with open(outside, "w", encoding="utf-8") as f: - f.write("outside-content") + 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", @@ -999,7 +998,7 @@ async def test_persistent_reset_workdir_each_call_does_not_restrict_file_access( by_path = await tool.run(f"cat '{outside}'") pwd = await tool.run("pwd") - moved_lines = moved.stdout.split() + 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" @@ -1008,7 +1007,7 @@ async def test_persistent_reset_workdir_each_call_does_not_restrict_file_access( def test_local_shell_tool_rejects_removed_confine_workdir_argument() -> None: with pytest.raises(TypeError): - LocalShellTool(confine_workdir=True) # type: ignore[call-arg] + LocalShellTool(**{"confine_workdir": True}) @pytest.mark.parametrize( From 049090ebf679089e00949be6099ddce1cfe4438a Mon Sep 17 00:00:00 2001 From: westey <164392973+westey-m@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:06:49 +0000 Subject: [PATCH 3/4] Fix typing errors --- python/packages/tools/tests/test_local_shell_tool.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/python/packages/tools/tests/test_local_shell_tool.py b/python/packages/tools/tests/test_local_shell_tool.py index 0c5f871c2f8..3b7db4f9e17 100644 --- a/python/packages/tools/tests/test_local_shell_tool.py +++ b/python/packages/tools/tests/test_local_shell_tool.py @@ -1005,11 +1005,6 @@ async def test_persistent_reset_workdir_each_call_does_not_restrict_file_access( assert os.path.realpath(pwd.stdout.strip()) == os.path.realpath(workdir) -def test_local_shell_tool_rejects_removed_confine_workdir_argument() -> None: - with pytest.raises(TypeError): - LocalShellTool(**{"confine_workdir": True}) - - @pytest.mark.parametrize( ("failure", "max_stderr_bytes"), [("timeout", 128), ("unrecoverable_timeout", 128), ("overflow", 1), ("overflow", 8192)], From e026b2ad5e516bd02f0b0f59dbbaee7b85d47332 Mon Sep 17 00:00:00 2001 From: westey <164392973+westey-m@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:20:25 +0000 Subject: [PATCH 4/4] Address PR comments --- .../Program.cs | 3 +-- .../Claw_Step03_ScalingCapabilities/README.md | 2 +- .../ClawAgent/ClawAgentFactory.cs | 1 - .../LocalShellExecutor.cs | 2 +- .../LocalShellExecutorOptions.cs | 17 +++++++----- .../LocalShellExecutorTests.cs | 9 +++---- python/packages/tools/README.md | 11 ++++---- .../agent_framework_tools/shell/_tool.py | 27 ++++++++++--------- .../tools/tests/test_local_shell_tool.py | 10 +++---- .../harness/build_your_own_claw/README.md | 2 +- .../claw_step03_scaling_capabilities.py | 3 +-- .../claw_step04_production_ready/agent.py | 1 - .../local_shell_with_environment_provider.py | 2 +- 13 files changed, 45 insertions(+), 45 deletions(-) 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 13331c42893..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 @@ -130,7 +130,7 @@ research before making decisions. // // -// A local shell that starts each command in the trade-confirmation vault. ResetWorkingDirectoryEachCall +// 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 @@ -138,7 +138,6 @@ research before making decisions. await using var shellExecutor = new LocalShellExecutor(new LocalShellExecutorOptions { WorkingDirectory = vaultDir, - ResetWorkingDirectoryEachCall = true, Policy = new ShellPolicy(denyList: [ @"\brm\s+-rf\b", 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 53d6226e383..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 @@ -15,7 +15,7 @@ It builds on Post 2's personal finance assistant and makes it *more capable* alo (opt-in; see below). - **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`). `ResetWorkingDirectoryEachCall` moves + `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 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 9200c8b3eff..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 @@ -154,7 +154,6 @@ public static async Task CreateAsync(ClawAgentFactoryOptions? op shell = new LocalShellExecutor(new LocalShellExecutorOptions { WorkingDirectory = vaultDir, - ResetWorkingDirectoryEachCall = true, Policy = new ShellPolicy(denyList: [ @"\brm\s+-rf\b", diff --git a/dotnet/src/Microsoft.Agents.AI.Tools.Shell/LocalShellExecutor.cs b/dotnet/src/Microsoft.Agents.AI.Tools.Shell/LocalShellExecutor.cs index 1ff0244d9c8..2b4ad9ee699 100644 --- a/dotnet/src/Microsoft.Agents.AI.Tools.Shell/LocalShellExecutor.cs +++ b/dotnet/src/Microsoft.Agents.AI.Tools.Shell/LocalShellExecutor.cs @@ -109,7 +109,7 @@ public LocalShellExecutor(LocalShellExecutorOptions options) this._timeout = options.Timeout; this._maxOutputBytes = options.MaxOutputBytes; this._workingDirectory = options.WorkingDirectory; - this._resetWorkingDirectoryEachCall = options.ResetWorkingDirectoryEachCall; + this._resetWorkingDirectoryEachCall = !options.DisableWorkingDirectoryResetOnEachCall; this._environment = options.Environment; this._cleanEnvironment = options.CleanEnvironment; this._acknowledgeUnsafe = options.AcknowledgeUnsafe; diff --git a/dotnet/src/Microsoft.Agents.AI.Tools.Shell/LocalShellExecutorOptions.cs b/dotnet/src/Microsoft.Agents.AI.Tools.Shell/LocalShellExecutorOptions.cs index d2921bca0ca..77079995f74 100644 --- a/dotnet/src/Microsoft.Agents.AI.Tools.Shell/LocalShellExecutorOptions.cs +++ b/dotnet/src/Microsoft.Agents.AI.Tools.Shell/LocalShellExecutorOptions.cs @@ -50,20 +50,23 @@ public sealed class LocalShellExecutorOptions /// Working directory for the spawned shell. Defaults to the current /// process directory. This is only where commands start; it does not /// limit which files a command can reach. - /// only has an effect when - /// this is set. + /// 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 cd in one call - /// doesn't carry over to the next. It has no effect in stateless mode, - /// where every command already starts in . + /// 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 + /// . /// /// - /// This does not restrict file access. It only sets where a command + /// 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 @@ -72,7 +75,7 @@ public sealed class LocalShellExecutorOptions /// commands can reach, use an executor with separately enforced isolation /// and restricted permissions, such as . /// - public bool ResetWorkingDirectoryEachCall { get; set; } = true; + public bool DisableWorkingDirectoryResetOnEachCall { get; set; } /// /// Extra environment variables. Pass a value to 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 1068d03a31a..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,7 +416,7 @@ public void Ctor_RejectsBothShellAndShellArgv() } [Fact] - public async Task Persistent_ResetWorkingDirectoryEachCall_StartsInWorkingDirectoryAfterCdAwayAsync() + public async Task Persistent_ByDefault_StartsInWorkingDirectoryAfterCdAwayAsync() { var rootDir = Path.GetTempPath(); var subDir = Path.Join(rootDir, "af-shell-reset-" + Guid.NewGuid().ToString("N")[..8]); @@ -427,7 +427,6 @@ public async Task Persistent_ResetWorkingDirectoryEachCall_StartsInWorkingDirect { Mode = ShellMode.Persistent, WorkingDirectory = rootDir, - ResetWorkingDirectoryEachCall = true, Timeout = TimeSpan.FromSeconds(20), }); @@ -452,7 +451,7 @@ public async Task Persistent_ResetWorkingDirectoryEachCall_StartsInWorkingDirect } [Fact] - public async Task Persistent_ResetWorkingDirectoryEachCall_DoesNotRestrictFileAccessAsync() + public async Task Persistent_WorkingDirectoryReset_DoesNotRestrictFileAccessAsync() { // Arrange var rootDir = Path.Join(Path.GetTempPath(), "af-shell-access-" + Guid.NewGuid().ToString("N")[..8]); @@ -493,7 +492,7 @@ public async Task Persistent_ResetWorkingDirectoryEachCall_DoesNotRestrictFileAc } [Fact] - public async Task Persistent_ResetWorkingDirectoryEachCallDisabled_AllowsCdToLeakAsync() + public async Task Persistent_DisableWorkingDirectoryResetOnEachCall_AllowsCdToLeakAsync() { var rootDir = Path.GetTempPath(); var subDir = Path.Join(rootDir, "af-shell-noreset-" + Guid.NewGuid().ToString("N")[..8]); @@ -504,7 +503,7 @@ public async Task Persistent_ResetWorkingDirectoryEachCallDisabled_AllowsCdToLea { Mode = ShellMode.Persistent, WorkingDirectory = rootDir, - ResetWorkingDirectoryEachCall = false, + DisableWorkingDirectoryResetOnEachCall = true, Timeout = TimeSpan.FromSeconds(20), }); diff --git a/python/packages/tools/README.md b/python/packages/tools/README.md index 0fda195ad72..d0057182fb4 100644 --- a/python/packages/tools/README.md +++ b/python/packages/tools/README.md @@ -81,11 +81,12 @@ 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 `reset_workdir_each_call` are **not** defenses. `workdir` is -only where commands start. `reset_workdir_each_call=True` (the default) moves -each persistent-mode command back to `workdir` before it runs, so a `cd` in -one call does not carry over to the next. It only has an effect when `workdir` -is set explicitly. Neither restricts file access: a +`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. diff --git a/python/packages/tools/agent_framework_tools/shell/_tool.py b/python/packages/tools/agent_framework_tools/shell/_tool.py index c93e56afaad..362adebd4d8 100644 --- a/python/packages/tools/agent_framework_tools/shell/_tool.py +++ b/python/packages/tools/agent_framework_tools/shell/_tool.py @@ -113,16 +113,17 @@ class LocalShellTool: workdir: Working directory for commands. Defaults to the current 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 when - ``reset_workdir_each_call=True`` — see that argument. - reset_workdir_each_call: When ``True`` (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. It only - has an effect when ``workdir`` is set explicitly. It has no - effect in stateless mode, where every command already starts in - ``workdir``. - - **This does not restrict file access.** It only sets where a + 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 @@ -179,7 +180,7 @@ def __init__( mode: ShellMode = "persistent", shell: str | Sequence[str] | None = None, workdir: str | os.PathLike[str] | None = None, - reset_workdir_each_call: bool = True, + disable_workdir_reset_on_each_call: bool = False, env: Mapping[str, str] | None = None, clean_env: bool = False, policy: ShellPolicy | None = None, @@ -206,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._reset_workdir_each_call = reset_workdir_each_call + 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 @@ -369,7 +370,7 @@ async def _run_shell(command: str) -> str: # ------------------------------------------------------------------ helpers def _maybe_reset_workdir(self, command: str) -> str: - """Prefix ``cd`` when ``reset_workdir_each_call`` is enabled and workdir is set.""" + """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 diff --git a/python/packages/tools/tests/test_local_shell_tool.py b/python/packages/tools/tests/test_local_shell_tool.py index 3b7db4f9e17..edfe8e47ca9 100644 --- a/python/packages/tools/tests/test_local_shell_tool.py +++ b/python/packages/tools/tests/test_local_shell_tool.py @@ -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), - reset_workdir_each_call=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), - reset_workdir_each_call=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") @@ -964,7 +964,7 @@ async def test_variable_shell_approval_cannot_be_replayed_on_later_turn_or_sessi @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: - """With the default ``reset_workdir_each_call=True``, a ``cd`` in one call + """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) @@ -980,8 +980,8 @@ async def test_persistent_resets_workdir_each_call_by_default(tmp_path: os.PathL @pytest.mark.skipif(sys.platform == "win32", reason="POSIX persistent workdir reset test") -async def test_persistent_reset_workdir_each_call_does_not_restrict_file_access(tmp_path: Path) -> None: - """``reset_workdir_each_call`` only sets where a command starts. A single +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" 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 9deb9ab846f..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 @@ -139,7 +139,7 @@ Makes the assistant *more capable* along four axes. Foundry Toolbox MCP endpoint via `MCPSkillsSource` (opt-in; see below). - **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`). `reset_workdir_each_call` moves every + `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 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 fac30c75e7d..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 @@ -260,7 +260,7 @@ def _build_research_agent(client: FoundryChatClient) -> Any: def _build_shell() -> LocalShellTool: """A local shell that starts each command in the trade-confirmation vault. - ``reset_workdir_each_call`` moves every command back to the vault before it runs, and the + 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 @@ -269,7 +269,6 @@ def _build_shell() -> LocalShellTool: return LocalShellTool( mode="persistent", workdir=str(_VAULT_DIR), - reset_workdir_each_call=True, policy=ShellPolicy( denylist=[ r"\brm\s+-rf\b", 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 9904a99aa57..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 @@ -258,7 +258,6 @@ def _build_shell() -> LocalShellTool: return LocalShellTool( mode="persistent", workdir=str(_VAULT_DIR), - reset_workdir_each_call=True, policy=ShellPolicy( denylist=[ r"\brm\s+-rf\b", 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 fed78578f16..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", - reset_workdir_each_call=False, + disable_workdir_reset_on_each_call=True, approval_mode="never_require", acknowledge_unsafe=True, ) as shell: