Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions packages/core/src/shell-encoding.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/** The text readers consume UTF-8, but Windows PowerShell inherits a legacy console encoding. */
export function windowsPowerShellCommand(shell: string, command: string, platform = process.platform): string {
if (platform !== "win32" || !/(?:^|[\\/])(?:powershell|pwsh)(?:\.exe)?$/i.test(shell)) return command
// Both the host's stdout/stderr and text piped to native commands must agree.
// Keep the original command on its own line, including leading comments.
return "$OutputEncoding = [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false);\n" + command
}
3 changes: 2 additions & 1 deletion packages/core/src/shell.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export * as Shell from "./shell"

import path from "path"
import { windowsPowerShellCommand } from "./shell-encoding"
import { spawn, type ChildProcess } from "child_process"
import { readFile } from "fs/promises"
import { statSync } from "fs"
Expand Down Expand Up @@ -197,7 +198,7 @@ export function args(file: string, command: string, cwd: string) {
]
}
if (n === "cmd") return ["/c", command]
if (ps(file)) return ["-NoProfile", "-Command", command]
if (ps(file)) return ["-NoProfile", "-Command", windowsPowerShellCommand(file, command)]
return ["-c", command]
}

Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/tool/bash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { ToolFailure } from "@opencode-ai/llm"
import { Duration, Effect, Layer, Schema } from "effect"
import { ChildProcess } from "effect/unstable/process"
import { Config } from "../config"
import { windowsPowerShellCommand } from "../shell-encoding"
import { makeLocationNode } from "../effect/app-node"
import { FSUtil } from "../fs-util"
import { LocationMutation } from "../location-mutation"
Expand Down Expand Up @@ -164,7 +165,7 @@ const layer = Layer.effectDiscard(
const shell =
Object.assign({}, ...entries.flatMap((entry) => (entry.type === "document" ? [entry.info] : [])))
.shell ?? defaultShell()
const command = ChildProcess.make(input.command, [], {
const command = ChildProcess.make(windowsPowerShellCommand(shell, input.command), [], {
cwd: target.canonical,
shell,
stdin: "ignore",
Expand Down
39 changes: 39 additions & 0 deletions packages/core/test/shell-encoding.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { describe, expect, test } from "bun:test"
import { spawnSync } from "node:child_process"
import { windowsPowerShellCommand } from "../src/shell-encoding"

const text = "Área de Trabalho - ação 日本語 😀"
const command = `[Console]::Write('${text}'); [Console]::Error.Write('${text}'); exit 7`
const pwsh = Bun.which("pwsh") || Bun.which("powershell")

describe("PowerShell UTF-8 output (#543)", () => {
test("initializes Windows PowerShell output without rewriting the command", () => {
const wrapped = windowsPowerShellCommand("C:\\tools\\PowerShell.EXE", command, "win32")
expect(wrapped).toContain("[Console]::OutputEncoding")
expect(wrapped).toContain("$OutputEncoding")
expect(wrapped.endsWith(command)).toBe(true)
expect(windowsPowerShellCommand("pwsh", command, "win32")).toBe(wrapped)
})

test("leaves POSIX shells and non-Windows PowerShell unchanged", () => {
for (const shell of ["cmd.exe", "C:\\Git\\bin\\bash.exe", "/bin/sh"])
expect(windowsPowerShellCommand(shell, command, "win32")).toBe(command)
expect(windowsPowerShellCommand("pwsh", command, "linux")).toBe(command)
})
;(pwsh ? test : test.skip)(
"real PowerShell restores UTF-8 stdout/stderr after a legacy codepage and preserves exit",
() => {
const setup = "[Console]::OutputEncoding = [System.Text.Encoding]::GetEncoding(1252);\n"
const invoke = (script: string) =>
spawnSync(pwsh!, ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script])
const before = invoke(setup + command)
expect(before.status).toBe(7)
expect(before.stdout.toString("utf8")).not.toBe(text)
const after = invoke(setup + windowsPowerShellCommand(pwsh!, command, "win32"))
expect(after.status).toBe(7)
expect(after.stdout.toString("utf8")).toBe(text)
expect(after.stderr.toString("utf8")).toBe(text)
expect(after.stdout.subarray(0, 3).equals(Buffer.from([0xef, 0xbb, 0xbf]))).toBe(false)
},
)
})
27 changes: 17 additions & 10 deletions packages/opencode/src/tool/shell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { fileURLToPath } from "url"
import { Config } from "@/config/config"
import { RuntimeFlags } from "@/effect/runtime-flags"
import { Shell } from "@opencode-ai/core/shell"
import { windowsPowerShellCommand } from "@opencode-ai/core/shell-encoding"
import { ShellID } from "./shell/id"
import { ToolFailure } from "@opencode-ai/llm"

Expand Down Expand Up @@ -294,15 +295,19 @@ const ask = Effect.fn("ShellTool.ask")(function* (ctx: Tool.Context, scan: Scan,

function cmd(shell: string, command: string, cwd: string, env: NodeJS.ProcessEnv) {
if (process.platform === "win32" && Shell.ps(shell)) {
return ChildProcess.make(shell, ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", command], {
cwd,
env,
stdin: "ignore",
detached: false,
// Bound scope-teardown kills: without this, a child that ignores SIGTERM
// hangs the finalizer forever and the session never leaves "running".
forceKillAfter: "3 seconds",
})
return ChildProcess.make(
shell,
["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", windowsPowerShellCommand(shell, command)],
{
cwd,
env,
stdin: "ignore",
detached: false,
// Bound scope-teardown kills: without this, a child that ignores SIGTERM
// hangs the finalizer forever and the session never leaves "running".
forceKillAfter: "3 seconds",
},
)
}

return ChildProcess.make(command, [], {
Expand Down Expand Up @@ -645,7 +650,9 @@ export const ShellTool = Tool.define(
}
if (aborted) meta.push("User aborted the command")
if (spillError) {
meta.push(`Could not save the full output to a file (${spillError.message}). The output below may be incomplete.`)
meta.push(
`Could not save the full output to a file (${spillError.message}). The output below may be incomplete.`,
)
file = ""
}
if (signaled) meta.push(`Command was terminated by signal ${signaled}`)
Expand Down
21 changes: 21 additions & 0 deletions packages/opencode/test/tool/shell.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,27 @@ const mustTruncate = (result: {
}

describe("tool.shell", () => {
for (const item of ps) {
it.live(`preserves non-ASCII PowerShell stdout/stderr and nonzero exit (#543) [${item.label}]`, () =>
withShell(
item,
runIn(
projectRoot,
Effect.gen(function* () {
const result = yield* run({
command:
"[Console]::Write('Área de Trabalho ação 日本語 😀'); [Console]::Error.Write('saída de erro'); exit 7",
})
expect(result.metadata.exit).toBe(7)
expect(result.output).toContain("Área de Trabalho ação 日本語 😀")
expect(result.output).toContain("saída de erro")
expect(result.output).not.toContain("\ufffd")
}),
),
),
)
}

each("basic", () =>
runIn(
projectRoot,
Expand Down
Loading