Skip to content

[Windows] PowerShell ConstrainedLanguage mode (WDAC/AppLocker): wrapper forces exitCode=1 on every succeeding command ($host.SetShouldExit) and aborts before execution when initScripts are present ($Error.RemoveAt) #5679

Backlog

Description

@ItsTimeToSnuff

Describe the bug

On enterprise-managed Windows machines where AppLocker / WDAC enforces PowerShell ConstrainedLanguage mode (standard Microsoft enterprise security baseline), the PowerShell wrapper hardcoded in prebuilds/win32-x64/runtime.node invokes .NET methods on non-core types (PSHost.SetShouldExit and ArrayList.RemoveAt), which PowerShell strictly prohibits in ConstrainedLanguage mode (MethodInvocationNotSupportedInConstrainedLanguage).

Important distinction from #4683: #4683 previously characterized $host.SetShouldExit() as cosmetic stderr noise with exit code 0. Session telemetry (events.jsonl) proves this is actually a functional regression with two distinct failure modes — forcing exitCode: 1 on 100% of successful commands, and completely preventing user commands from executing when host ShellOptions.initScripts are present (e.g., in the JetBrains IDE integration).


Failure Mode 1: Every successful command terminates with exitCode: 1 ($host.SetShouldExit)

At the end of every command, runtime.node appends a finally epilogue:

} finally { $__copilotSuccess = $?; if (-not $__copilotSuccess -and $LASTEXITCODE -is [int] -and $LASTEXITCODE -ne 0) { $host.SetShouldExit($LASTEXITCODE) } elseif (-not $__copilotSuccess) { $host.SetShouldExit(1) } else { $host.SetShouldExit(0) } }

Because $host (System.Management.Automation.Host.PSHost) is not on PowerShell's ConstrainedLanguage allowed core-type list, $host.SetShouldExit(0) throws an unhandled RuntimeException inside finally, causing the shell execution to complete with exitCode: 1:

Cannot invoke method. Method invocation is supported only on core types in this language mode.
At line:5 char:234
+ ... ccess) { $host.SetShouldExit(1) } else { $host.SetShouldExit(0) } } }
+                                              ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodInvocationNotSupportedInConstrainedLanguage
<shellId: 59 completed with exit code 1>

Recorded tool.execution_complete event in ~/.copilot/session-state/<session-id>/events.jsonl:

{
  "type": "tool.execution_complete",
  "data": {
    "shellExecution": { "exitCode": 1 },
    "toolTelemetry": {
      "properties": {
        "executionMode": "sync",
        "sandboxApplied": "false",
        "shell_error_category": "command_nonzero_exit"
      },
      "metrics": { "exit_code": 1.0 }
    }
  }
}

Impact:

  • In IDE hosts (copilot-intellij, VS Code), every single shell tool call in the UI is marked as failed (×, exit code 1) even when git, python, gradle, etc. succeeded with exit code 0.
  • Agents misinterpret exitCode: 1 as command failure, retrying idempotent/non-idempotent commands or abandoning valid workflows.
  • Corrupts shell_error_category: "command_nonzero_exit" metrics across all enterprise Windows users.

Failure Mode 2: Complete shell tool outage before user command runs ($Error.RemoveAt(0))

When an SDK/IDE host (such as copilot-intellij) supplies ShellOptions.initScripts, the init script fails under ConstrainedLanguage mode. The wrapper prints a warning claiming it will continue with the user command, and immediately executes its own error-cleanup line:

if ($Error.Count -gt $__copilotPreviousErrorCount) { $Error.RemoveAt(0) }

$Error is a System.Collections.ArrayList (also a non-core .NET type). Calling .RemoveAt(0) throws an unhandled ParentContainsErrorRecordException (MethodInvocationNotSupportedInConstrainedLanguage) outside the try/catch, aborting the PowerShell process with exit code 1 before the user command is ever reached:

copilot: shell init script failed; continuing with remaining scripts and the user command
Cannot invoke method. Method invocation is supported only on core types in this language mode.
At line:9 char:57
+ ... $Error.Count -gt $__copilotPreviousErrorCount) { $Error.RemoveAt(0) }
+                                                      ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MethodInvocationNotSupportedInConstrainedLanguage
<shellId: 78 completed with exit code 1>

Token & Latency Impact (verified in session trace):
Because the error looks like a script failure, the model enters a blind troubleshooting loop — burning 5 consecutive LLM turns (7 powershell tool calls, ~300k+ cached/input tokens and >2 minutes of latency) attempting to simplify commands down to bare Write-Output, none of which ever reach execution. On Turn 6, the agent bypassed PowerShell via the JetBrains MCP execute_terminal_command (executeInShell: false) to invoke python directly, and the exact same script succeeded on the first try (exitCode: 0). This confirms both severe token/quota waste across enterprise sessions and 100% isolation of the bug to Copilot's PowerShell wrapper.


Why zero client-side workarounds exist for enterprise users

  1. Cannot be bypassed via flags or PowerShell 7: WDAC / AppLocker enforces ConstrainedLanguage system-wide via SystemPolicy.GetSystemLockdownPolicy(). Passing powershellFlags (-ExecutionPolicy Bypass, -NoProfile) in ~/.copilot/settings.json or installing pwsh.exe (PowerShell 7+) does not switch LanguageMode to FullLanguage.
  2. Shell selection is hardcoded on Windows: runtime.node unconditionally spawns PowerShell (pwsh.exe / powershell.exe) on Windows and ignores IDE terminal settings (Settings -> Tools -> Terminal -> Shell path), COMSPEC, and SHELL, so users cannot switch the built-in shell tool to cmd.exe or Git bash.exe.

Concrete, ConstrainedLanguage-safe fix

Both failures come exclusively from .NET method calls in Copilot's generated wrapper and can be fixed using pure PowerShell language primitives permitted in both FullLanguage and ConstrainedLanguage (PS 5.1 and PS 7+):

  1. Replace $host.SetShouldExit(...) with a top-level exit keyword after finally:

    $__copilotExitCode = 1
    try {
        # ... user command ...
    } finally {
        $__copilotSuccess = $?
        if (-not $__copilotSuccess -and $LASTEXITCODE -is [int] -and $LASTEXITCODE -ne 0) {
            $__copilotExitCode = $LASTEXITCODE
        } elseif (-not $__copilotSuccess) {
            $__copilotExitCode = 1
        } else {
            $__copilotExitCode = 0
        }
    }
    exit $__copilotExitCode

    exit <int> at script/command scope preserves exact numeric exit codes (including hook exit code 2) under -Command without invoking any .NET methods on $host.

  2. Guard or eliminate $Error.RemoveAt(0) in initScripts cleanup:
    Property reads (.LanguageMode, .Count) are allowed in ConstrainedLanguage, whereas .RemoveAt(...) / .Clear() are blocked. Either guard the mutation:

    if ($ExecutionContext.SessionState.LanguageMode -eq 'FullLanguage') {
        while ($Error.Count -gt $__copilotPreviousErrorCount) { $Error.RemoveAt(0) }
    }

    or reset $? before the user command without mutating $Error (e.g., $null = $true).

Affected version

1.0.105

Steps to reproduce the behavior

  1. On a Windows 10/11 enterprise machine where AppLocker or WDAC enforces PowerShell ConstrainedLanguage mode ($ExecutionContext.SessionState.LanguageMode == ConstrainedLanguage; reproducible locally in an elevated prompt via [Environment]::SetEnvironmentVariable('__PSLockdownPolicy', '4', 'Machine') and opening a new process).
  2. Start a Copilot Agent session (via copilot CLI or GitHub Copilot Plugin for JetBrains 1.22.0-261) and let the agent invoke the powershell tool with any succeeding command, e.g.:
    git --no-pager status --short --branch or Write-Output "hello"
  3. Without initScripts: Observe that git status prints valid output, followed by MethodInvocationNotSupportedInConstrainedLanguage at $host.SetShouldExit(0) and <shellId: N completed with exit code 1>, marking the tool call as failed (×) in the UI.
  4. With host ShellOptions.initScripts present: Observe copilot: shell init script failed; continuing with remaining scripts and the user command, followed immediately by MethodInvocationNotSupportedInConstrainedLanguage at $Error.RemoveAt(0) — the user command never executes at all.

Expected behavior

  1. Succeeding commands executed via the powershell tool under Windows ConstrainedLanguage mode complete with exitCode: 0, emit no wrapper RuntimeException to output/stderr, and render as succeeded in CLI and IDE hosts.
  2. When a non-fatal ShellOptions.initScripts script fails under ConstrainedLanguage mode, the wrapper's error-cleanup logic does not throw an unhandled MethodInvocationNotSupportedInConstrainedLanguage exception and proceeds to execute the user command as stated by its warning message.

Additional context

  • Operating system: Windows 11 Enterprise x64 (domain-joined, AppLocker/WDAC endpoint security policy enforcing ConstrainedLanguage)
  • CPU architecture: x86_64 (@github/copilot-win32-x64)
  • Shell: Windows PowerShell 5.1 (C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe); affects PowerShell 7 (pwsh.exe) identically when ConstrainedLanguage is enforced by WDAC/AppLocker
  • Host / Client: copilot-intellij (1.22.0-261-windows-x64) on IntelliJ IDEA 2026.3.0.1 + Copilot Agent Runtime 1.0.105
  • Related issues: Every shell command emits a spurious error under PowerShell ConstrainedLanguage mode (AppLocker/WDAC): $host.SetShouldExit() is not permitted #4683 (covers $host.SetShouldExit, but mistakenly reported exit code as 0; does not cover exitCode: 1 telemetry/UI failure or the fatal $Error.RemoveAt(0) crash with initScripts in 1.0.105+)

Activity

  1. added
    area:enterprise
    area:platform-windows
    area:tools
    and removed on Dec 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:enterprisearea:platform-windowsarea:tools

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions