feat(cli): discover Bash for Windows runners

Use Pi-style Bash discovery and launch behavior, exercise the packaged CLI shell, and wait for pending ZIP metadata reads before closing cancelled downloads.
This commit is contained in:
yiling
2026-11-18 10:57:04 +08:00
parent 776f6962b6
commit fd4dc211f8
18 changed files with 453 additions and 63 deletions
+3 -3
View File
@@ -106,7 +106,7 @@ shumai-cli runner start --cwd C:\workspace
Use `--url` or `--key` to override those variables. A runner key is separate from `SHUMAI_API_KEY`. The runner stays in the foreground; Ctrl+C stops it and its active commands. Remote servers require HTTPS; localhost and `host.docker.internal` support HTTP for development. No inbound port is opened.
Commands use `/bin/sh` on macOS/Linux and `cmd.exe` on Windows. The agent receives the runner's OS and shell so it can use the appropriate syntax. Commands run with the local user's permissions unless SRT is requested.
Commands use `/bin/sh` on macOS and Linux. On Windows, the runner checks for Git Bash in the standard installation directories, then for `bash.exe` on PATH, then falls back to `cmd.exe`. It prints the selected shell at startup and reports it to the agent. Commands run with the local user's permissions unless SRT is requested.
[Anthropic Sandbox Runtime](https://github.com/anthropics/sandbox-runtime) is bundled with the CLI. Install its platform prerequisites (Linux: bubblewrap, socat, and ripgrep; macOS: ripgrep), then pass its native JSON settings:
@@ -114,7 +114,7 @@ Commands use `/bin/sh` on macOS/Linux and `cmd.exe` on Windows. The agent receiv
shumai-cli runner start --srt sandbox.json
```
Windows sandboxing uses SRT's alpha Windows support. Run its one-time setup before starting a sandboxed runner (it requests administrator permission):
Windows sandboxing uses SRT's alpha Windows support. Use Git Bash if your selected shell is the legacy WSL Bash launcher. Run the one-time SRT setup before starting a sandboxed runner (it requests administrator permission):
```powershell
npx @anthropic-ai/sandbox-runtime windows-install
@@ -368,7 +368,7 @@ bun run build:cli --target darwin-arm64 # or darwin-x64, linux-arm64, linux-x64,
bun run test:cli-release
```
Without `--target`, the build produces all six targets. Output defaults to `out/cli-release`; both commands accept `--out /absolute/path`. Unix archives require `tar`; creating Windows archives on Unix also requires `zip`. The test runs the generated installer against local HTTP fixtures, then authenticates, creates a folder, uploads and downloads random bytes, and checks failure recovery with no runtime on the executable's PATH.
Without `--target`, the build produces all six targets. Output defaults to `out/cli-release`. Set `--out /absolute/path` on either command to change it. Unix archives require `tar`. Creating Windows archives on Unix also requires `zip`. The test exercises installation, runner shell quoting, authenticated API calls, file transfers, and failure recovery. Install Git Bash to run the quoting check on Windows. With SRT configured, pass `--srt /absolute/path/to/settings.json` to repeat the quoting check in the sandbox.
The Native CLI workflow builds and tests each target on a matching runner. The npm release workflow assembles those tested archives, stages a draft GitHub Release, publishes npm packages, then publishes the completed release. Its `validate_only` dispatch input builds and tests without publishing. Published assets are verified and preserved on retries; draft assets can be replaced while resuming a failed run. Prerelease npm packages use the `next` tag and prerelease GitHub Releases do not become latest.
+24
View File
@@ -0,0 +1,24 @@
The Windows Bash discovery and related tests include material adapted from Pi.
https://github.com/earendil-works/pi
MIT License
Copyright (c) 2025 Mario Zechner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+3 -2
View File
@@ -291,11 +291,12 @@ export class RunnerClient {
export async function startRunner(options: RunnerOptions) {
const config = await resolveRunnerConfig(options)
// SRT resolves relative policy paths against the runner workspace.
process.chdir(config.cwd)
const files = new RunnerFiles(config.cwd)
const shell = new RunnerShell(files, config.srt)
// SRT resolves relative policy paths against the runner workspace.
process.chdir(config.cwd)
await shell.initialize()
console.error(`Runner shell: ${shell.environment.shell}`)
const runner = new RunnerClient(config, files, shell)
const controller = new AbortController()
const shutdown = () => controller.abort()
+1 -8
View File
@@ -1,16 +1,9 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { commandEnv, resolveRunnerConfig, runnerShell } from './config'
import { commandEnv, resolveRunnerConfig } from './config'
afterEach(() => vi.unstubAllEnvs())
describe('runner configuration', () => {
it('uses the platform shell without requiring Bash on Windows', () => {
vi.stubEnv('SystemRoot', 'D:\\Windows')
expect(runnerShell('win32')).toBe('D:\\Windows\\System32\\cmd.exe')
expect(runnerShell('linux')).toBe('/bin/sh')
expect(runnerShell('darwin')).toBe('/bin/sh')
})
it('preserves Windows OS settings, normalizes explicit overrides, and excludes credentials', () => {
vi.stubEnv('Path', 'C:\\Windows\\System32')
vi.stubEnv('SystemRoot', 'C:\\Windows')
-6
View File
@@ -44,12 +44,6 @@ export async function resolveRunnerConfig(options: RunnerOptions) {
return { url, key: key.trim(), cwd, srt: options.srt ? path.resolve(options.srt) : undefined }
}
export function runnerShell(platform = process.platform): string {
return platform === 'win32'
? path.win32.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'cmd.exe')
: '/bin/sh'
}
/** Commands inherit baseline OS settings and explicitly supplied skill variables, never CLI credentials. */
export function commandEnv(extra: Record<string, string> = {}, inherit = true): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = {}
+39
View File
@@ -5,6 +5,7 @@ import { tmpdir } from 'node:os'
import path from 'node:path'
import AdmZip from 'adm-zip'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import yauzl from 'yauzl'
import { RunnerFiles } from './files'
describe('runner workspace file transfers', () => {
@@ -305,6 +306,44 @@ describe('runner workspace file transfers', () => {
expect(await readdir(path.join(cwd, '.pi/skills'))).toEqual(['installed'])
}, 10000)
it('waits for an in-flight ZIP entry read before closing on cancellation', async () => {
const zip = new AdmZip()
zip.addFile('SKILL.md', Buffer.from('skill'))
body = zip.toBuffer()
const controller = new AbortController()
const pendingRead = Promise.withResolvers<() => void>()
const readEntry = yauzl.ZipFile.prototype.readEntry
const read = vi.spyOn(yauzl.ZipFile.prototype, 'readEntry').mockImplementationOnce(function (
this: yauzl.ZipFile,
) {
pendingRead.resolve(() => readEntry.call(this))
})
const close = vi.spyOn(yauzl.ZipFile.prototype, 'close')
try {
const transfer = files.handle(
{
type: 'file.download',
executionId: 'zip-entry-cancel',
url,
destPath: '.pi/skills/new',
extractZip: true,
},
controller.signal,
)
const finishRead = await pendingRead.promise
controller.abort()
await new Promise<void>((resolve) => setImmediate(resolve))
const closedDuringRead = close.mock.calls.length > 0
if (!closedDuringRead) finishRead()
expect(await transfer).toHaveProperty('ok', false)
expect(closedDuringRead).toBe(false)
expect(await readdir(path.join(cwd, '.pi/skills'))).toEqual([])
} finally {
read.mockRestore()
close.mockRestore()
}
})
it('handles cancelled transfers and refuses uploads of directories', async () => {
const controller = new AbortController()
controller.abort()
+10 -15
View File
@@ -1,5 +1,4 @@
import { createHash } from 'node:crypto'
import { on } from 'node:events'
import { constants, createWriteStream } from 'node:fs'
import { lstat, mkdir, mkdtemp, open, rename, rm } from 'node:fs/promises'
import path from 'node:path'
@@ -244,19 +243,18 @@ export class RunnerFiles {
}
private async extract(archive: string, directory: string, signal: AbortSignal) {
const zip = await new Promise<yauzl.ZipFile>((resolve, reject) =>
yauzl.open(
archive,
{ lazyEntries: true, strictFileNames: true, autoClose: false },
(error, opened) => (error ? reject(error) : resolve(opened)),
),
)
const zip = await yauzl.openPromise(archive, {
lazyEntries: true,
strictFileNames: true,
autoClose: false,
})
let size = 0
let count = 0
try {
const entries = on(zip, 'entry', { close: ['end'], signal }) as AsyncIterable<[yauzl.Entry]>
zip.readEntry()
for await (const [entry] of entries) {
signal.throwIfAborted()
// Let each metadata read finish before cancellation can close the ZIP descriptor.
for await (const entry of zip.eachEntry()) {
signal.throwIfAborted()
if (++count > MAX_ZIP_ENTRIES) throw new Error('ZIP contains too many entries.')
const parts = pathParts(entry.fileName.replace(/\/$/, ''))
const mode = entry.externalFileAttributes >>> 16
@@ -269,16 +267,13 @@ export class RunnerFiles {
if (entry.fileName.endsWith('/')) await mkdir(destination, { recursive: true, mode: 0o700 })
else {
await mkdir(path.dirname(destination), { recursive: true, mode: 0o700 })
const input = await new Promise<Readable>((resolve, reject) =>
zip.openReadStream(entry, (error, stream) => (error ? reject(error) : resolve(stream))),
)
const input = await zip.openReadStreamPromise(entry)
await pipeline(
input,
createWriteStream(destination, { flags: 'wx', mode: 0o600 | (mode & 0o155) }),
{ signal },
)
}
zip.readEntry()
}
} finally {
zip.close()
+106
View File
@@ -0,0 +1,106 @@
import { spawnSync, type SpawnSyncReturns } from 'node:child_process'
import { accessSync, constants } from 'node:fs'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { resolveRunnerShell } from './shell-config'
vi.mock('node:child_process', () => ({ spawnSync: vi.fn() }))
vi.mock('node:fs', { spy: true })
const access = vi.mocked(accessSync)
const where = vi.mocked(spawnSync)
const gitBash = 'D:\\Program Files\\Git\\bin\\bash.exe'
const gitBashX86 = 'D:\\Program Files (x86)\\Git\\bin\\bash.exe'
function whereResult(stdout = '', status = 0): SpawnSyncReturns<string> {
return { stdout, stderr: '', status, output: [null, stdout, ''], pid: 1, signal: null }
}
function available(...paths: string[]) {
access.mockImplementation((executable) => {
if (!paths.some((path) => executable === path)) throw new Error('File not found')
})
}
beforeEach(() => {
vi.stubEnv('ProgramFiles', 'D:\\Program Files')
vi.stubEnv('ProgramFiles(x86)', 'D:\\Program Files (x86)')
vi.stubEnv('SystemRoot', 'E:\\WinNT')
available()
where.mockReturnValue(whereResult('', 1))
})
afterEach(() => {
vi.resetAllMocks()
vi.unstubAllEnvs()
})
describe('runner shell selection', () => {
it.each(['linux', 'darwin'] as const)('uses /bin/sh on %s', (platform) => {
expect(resolveRunnerShell(platform)).toEqual({
executable: '/bin/sh',
commandTransport: 'shell',
})
expect(where).not.toHaveBeenCalled()
})
it.each([
[gitBash, [gitBash, gitBashX86]],
[gitBashX86, [gitBashX86]],
] as const)('prefers installed Git Bash at %s before PATH', (executable, paths) => {
available(...paths)
expect(resolveRunnerShell('win32')).toEqual({ executable, commandTransport: 'argv' })
expect(where).not.toHaveBeenCalled()
})
// Adapted from Pi's shell-path-exists.test.ts. See apps/cli/THIRD-PARTY-NOTICES.txt.
it('accepts a Windows Store Bash alias found on PATH via access(F_OK)', () => {
const alias = 'D:\\Users\\runner\\AppData\\Local\\Microsoft\\WindowsApps\\bash.exe'
available(alias)
where.mockReturnValue(whereResult(alias + '\r\n'))
expect(resolveRunnerShell('win32')).toEqual({ executable: alias, commandTransport: 'argv' })
expect(access).toHaveBeenCalledWith(alias, constants.F_OK)
expect(where).toHaveBeenCalledWith('E:\\WinNT\\System32\\where.exe', ['$PATH:bash.exe'], {
encoding: 'utf8',
timeout: 5000,
windowsHide: true,
})
})
it('skips relative and inaccessible PATH results', () => {
const executable = 'D:\\MSYS2\\usr\\bin\\bash.exe'
available(executable)
where.mockReturnValue(
whereResult(['bash.exe', 'D:\\missing\\bash.exe', executable].join('\r\n')),
)
expect(resolveRunnerShell('win32')).toEqual({ executable, commandTransport: 'argv' })
})
it.each([
['E:\\WinNT', 'E:\\WinNT\\System32\\cmd.exe'],
[undefined, 'C:\\Windows\\System32\\cmd.exe'],
] as const)(
'falls back to cmd.exe when no Bash is available (SystemRoot %s)',
(root, executable) => {
vi.stubEnv('SystemRoot', root)
expect(resolveRunnerShell('win32')).toEqual({ executable, commandTransport: 'shell' })
},
)
// Adapted from Pi's windows-shell-config.test.ts.
it.each([
['D:\\WinNT\\', 'd:/WINNT/System32/BASH.EXE', 'stdin'],
['D:\\WinNT', 'D:\\WinNT\\Sysnative\\bash.exe', 'stdin'],
[undefined, 'E:\\Windows\\System32\\bash.exe', 'stdin'],
['D:\\WinNT', 'D:\\Git\\bin\\bash.exe', 'argv'],
['D:\\WinNT', 'E:\\Windows\\System32\\bash.exe', 'argv'],
['WinNT', 'C:\\Windows\\System32\\bash.exe', 'argv'],
] as const)(
'uses the correct command transport for SystemRoot %s and %s',
(root, executable, commandTransport) => {
vi.stubEnv('SystemRoot', root)
available(executable)
where.mockReturnValue(whereResult(executable + '\r\n'))
expect(resolveRunnerShell('win32')).toEqual({ executable, commandTransport })
},
)
})
+64
View File
@@ -0,0 +1,64 @@
import { spawnSync } from 'node:child_process'
import { accessSync, constants } from 'node:fs'
import { win32 } from 'node:path'
export interface RunnerShellConfig {
executable: string
commandTransport: 'shell' | 'argv' | 'stdin'
}
// Windows Bash discovery and legacy WSL detection adapted from pi-mono.
// See apps/cli/THIRD-PARTY-NOTICES.txt.
function isLegacyWslBashPath(executable: string, systemRoot: string | undefined): boolean {
const normalized = win32.normalize(executable).toLowerCase()
if (systemRoot) {
if (!/^[a-z]:[\\/]/i.test(systemRoot)) return false
return ['System32', 'Sysnative'].some(
(directory) => normalized === win32.join(systemRoot, directory, 'bash.exe').toLowerCase(),
)
}
return /^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(normalized)
}
function shellPathExists(executable: string): boolean {
// access(F_OK) accepts runnable Windows Store aliases that fail an extra stat check.
try {
accessSync(executable, constants.F_OK)
return true
} catch {
return false
}
}
function findWindowsBash(system32: string): string | undefined {
for (const directory of [process.env.ProgramFiles, process.env['ProgramFiles(x86)']]) {
if (!directory || !win32.isAbsolute(directory)) continue
const executable = win32.join(directory, 'Git', 'bin', 'bash.exe')
if (shellPathExists(executable)) return executable
}
// Use the system tool and limit its search to PATH. The workspace may contain a bash.exe.
const found = spawnSync(win32.join(system32, 'where.exe'), ['$PATH:bash.exe'], {
encoding: 'utf8',
timeout: 5000,
windowsHide: true,
})
if (found.status !== 0 || !found.stdout) return
return found.stdout
.trim()
.split(/\r?\n/)
.find((executable) => win32.isAbsolute(executable) && shellPathExists(executable))
}
export function resolveRunnerShell(platform = process.platform): RunnerShellConfig {
if (platform !== 'win32') return { executable: '/bin/sh', commandTransport: 'shell' }
const systemRoot = process.env.SystemRoot
const system32 = win32.join(systemRoot ?? 'C:\\Windows', 'System32')
const executable = findWindowsBash(system32)
if (!executable) return { executable: win32.join(system32, 'cmd.exe'), commandTransport: 'shell' }
return {
executable,
commandTransport: isLegacyWslBashPath(executable, systemRoot) ? 'stdin' : 'argv',
}
}
+55 -1
View File
@@ -47,6 +47,57 @@ describe('runner bash execution', () => {
expect(output).toBe('no-extra-runtime')
})
// Adapted from Pi's tools.test.ts. See apps/cli/THIRD-PARTY-NOTICES.txt.
it('sends the complete command over stdin for the legacy Bash launcher', async () => {
shell = new RunnerShell(new RunnerFiles(cwd), undefined, {
executable: '/bin/sh',
commandTransport: 'stdin',
})
const command = [
'name="Hello, 世界"',
'for choice in "one two" \'three "four"\'; do',
' printf \'%s / %s\\n\' "$name" "$choice"',
'done',
].join('\n')
let output = ''
const result = await shell.run(
request(command),
new AbortController().signal,
(_stream, data) => {
output += data
},
)
expect(result).toMatchObject({ exitCode: 0 })
expect(output).toBe('Hello, 世界 / one two\nHello, 世界 / three "four"\n')
})
it('passes a command with shell quoting directly to the selected executable', async () => {
shell = new RunnerShell(new RunnerFiles(cwd), undefined, {
executable: '/bin/sh',
commandTransport: 'argv',
})
const command = "printf '%s' '$literal \"quotes\"'"
let output = ''
const result = await shell.run(
request(command),
new AbortController().signal,
(_stream, data) => {
output += data
},
)
expect(result).toMatchObject({ exitCode: 0 })
expect(output).toBe('$literal "quotes"')
})
it('rejects the legacy WSL launcher before starting SRT', async () => {
shell = new RunnerShell(new RunnerFiles(cwd), path.join(cwd, 'sandbox.json'), {
executable: 'C:\\Windows\\System32\\bash.exe',
commandTransport: 'stdin',
})
await expect(shell.initialize()).rejects.toThrow('SRT cannot run the legacy WSL Bash launcher')
expect(SandboxManager.initialize).not.toHaveBeenCalled()
})
it('streams both outputs, returns the exit code, and saves a log in the runner workspace', async () => {
const output: string[] = []
const result = await shell.run(
@@ -125,7 +176,10 @@ describe('runner bash execution', () => {
})
it('reports launch failure without including command text or skill secrets', async () => {
shell.environment.shell = path.join(cwd, 'missing-shell')
shell = new RunnerShell(new RunnerFiles(cwd), undefined, {
executable: path.join(cwd, 'missing-shell'),
commandTransport: 'shell',
})
const result = await shell.run(
request('echo private-command'),
new AbortController().signal,
+23 -11
View File
@@ -3,21 +3,20 @@ import { execa } from 'execa'
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
import {
runnerEnvironmentSchema,
type RunnerEnvironment,
type RunnerExecResultMessage,
type RunnerExecStartMessage,
} from '@shumai/dtos'
import { commandEnv, runnerShell } from './config'
import { commandEnv } from './config'
import { RunnerFiles } from './files'
import { resolveRunnerShell } from './shell-config'
import { loadSandbox } from './srt'
const MAX_OUTPUT_BYTES = 64 * 1024 * 1024
const MAX_TIMEOUT_SEC = 3600
export class RunnerShell {
readonly environment = runnerEnvironmentSchema.parse({
platform: process.platform,
shell: runnerShell(),
})
readonly environment: RunnerEnvironment
private sandbox?: Awaited<ReturnType<typeof loadSandbox>>
private initialized = false
private active = 0
@@ -25,10 +24,20 @@ export class RunnerShell {
constructor(
private readonly files: RunnerFiles,
private readonly srtPath?: string,
) {}
private readonly config = resolveRunnerShell(),
) {
this.environment = runnerEnvironmentSchema.parse({
platform: process.platform,
shell: config.executable,
})
}
async initialize() {
if (!this.srtPath) return
if (this.config.commandTransport === 'stdin')
throw new Error(
'SRT cannot run the legacy WSL Bash launcher. Install Git for Windows to use Bash with SRT.',
)
// Read and validate once; commands cannot weaken the policy by editing the file.
this.sandbox = await loadSandbox(this.srtPath)
try {
@@ -86,9 +95,12 @@ export class RunnerShell {
const log = await this.files.createWriter(logPath)
try {
const windows = process.platform === 'win32'
let args: string[] = []
let executable = message.command
let shell: string | false = this.environment.shell
const { commandTransport } = this.config
const useShell = commandTransport === 'shell'
const sendCommandOnStdin = commandTransport === 'stdin'
let executable = useShell ? message.command : this.config.executable
let args = useShell ? [] : sendCommandOnStdin ? ['-s'] : ['-c', message.command]
let shell: string | false = useShell && this.config.executable
let env = commandEnv(message.env)
if (this.srtPath) {
if (!this.initialized) throw new Error('SRT has not been initialized.')
@@ -103,7 +115,7 @@ export class RunnerShell {
].join('\n')
const wrapped = await SandboxManager.wrapWithSandboxArgv(
command,
this.environment.shell,
this.config.executable,
undefined,
signal,
this.files.cwd,
@@ -131,7 +143,7 @@ export class RunnerShell {
env,
extendEnv: false,
shell,
stdin: 'ignore',
stdin: sendCommandOnStdin ? [Buffer.from(message.command)] : 'ignore',
buffer: false,
reject: false,
stripFinalNewline: false,