Files
a0-launcher/shell/docker_adapter/impl/WindowsWslRuntime.mjs
Alessandro f324a852a1 Use Debian slim for fresh Windows WSL runtimes
Import a checksum-pinned Debian 13 slim rootfs when Windows needs a new
WSL2 runtime. Install Docker Engine and the Python dependency for the
Launcher bridge, and enable Docker on the managed distro's boot.

Keep existing Ubuntu and Docker Desktop runtimes reusable. Update the
setup checklist, troubleshooting guidance, and regression tests.
2026-11-23 18:14:50 +01:00

626 lines
26 KiB
JavaScript

/**
* Windows runtime assessment for Docker Desktop and WSL-backed Docker Engine.
*
* DockerInterface probing runs before this class is consulted. This provisioner
* can start Docker Desktop when it is installed, or start an already-installed
* WSL Docker Engine behind a Windows loopback bridge. Windows client WSL setup
* is explicit and goes through a user-approved UAC prompt when Windows features
* need administrator rights.
*/
import { RuntimeProvisioner, makeError, run, sleep, tail } from '../RuntimeProvisioner.mjs';
import { DockerHubRegistry } from './DockerHubRegistry.mjs';
import { ensureWindowsWslDockerProxy } from './WindowsWslDockerProxy.mjs';
import { MANAGED_WSL_DISTRO, selectWindowsWslDistro } from './WindowsWslDistros.mjs';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
const WSL_GUIDE_URL = 'https://learn.microsoft.com/windows/wsl/install-on-server';
const WSL_INSTALL_URL = 'https://learn.microsoft.com/windows/wsl/install';
const DOCKER_ENGINE_URL = 'https://docs.docker.com/engine/install/';
const DOCKER_DESKTOP_URL = 'https://www.docker.com/products/docker-desktop/';
const WSL_DOCKER_HOST = 'tcp://127.0.0.1:23750';
// The single gzip layers from the official Debian trixie-20261104-slim OCI manifests.
const DEBIAN_ROOTFS = {
amd64: '37fb86c2a767b88d500c6872195f88078f64765fe0d2f9cc375cc2efbd4c0a41',
arm64: 'acd43e9bebc37bc4ba7a5f47bd7598913337803e53d468f37d940f11f5d5f1ef'
};
export class WindowsWslRuntime extends RuntimeProvisioner {
constructor(options = {}) {
super(options);
this._runCommand = typeof options.runCommand === 'function' ? options.runCommand : run;
this._ensureProxy = typeof options.ensureProxy === 'function' ? options.ensureProxy : ensureWindowsWslDockerProxy;
this._isWindowsServerOverride = typeof options.isWindowsServer === 'boolean' ? options.isWindowsServer : null;
this.wslInstallDir = path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'agent-zero', 'wsl', MANAGED_WSL_DISTRO);
}
async assess() {
const isServer = await this.#isWindowsServer();
if (!isServer) {
return await this.#assessWindowsClient();
}
const wslPresent = await this.#binaryExists('wsl.exe');
if (!wslPresent) {
return {
state: 'manual_install',
detail: 'Docker Desktop is not supported on Windows Server. Install WSL2 with nested virtualization support, then provide a Linux-container Docker Engine endpoint.',
manualUrl: WSL_GUIDE_URL
};
}
const distroList = await this.#wslList();
const wslUsable = this.#wslListShowsUsableFeatures(distroList);
const wslFeature = await this.#optionalFeatureState('Microsoft-Windows-Subsystem-Linux');
const vmPlatform = await this.#optionalFeatureState('VirtualMachinePlatform');
if (!wslUsable && (wslFeature !== 'Enabled' || vmPlatform !== 'Enabled')) {
return {
state: 'manual_install',
detail: 'Docker Desktop is not supported on Windows Server. Enable WSL2 with wsl.exe --install --no-distribution, restart Windows, then provide a Linux-container Docker Engine endpoint.',
manualCommand: 'wsl.exe --install --no-distribution',
manualUrl: WSL_GUIDE_URL
};
}
if (/WSL_E_DEFAULT_DISTRO_NOT_FOUND|has no installed distributions|no installed distributions|non ha distribuzioni installate/i.test(distroList)) {
return {
state: 'manual_install',
detail: 'WSL2 is enabled, but no Linux Docker Engine is available yet. Install a WSL distro with Docker Engine. If WSL2 cannot start, this VM needs nested virtualization or Hyper-V support from the host provider.',
manualUrl: WSL_GUIDE_URL
};
}
return {
state: 'manual_install',
detail: 'A WSL distro is installed, but no Windows Docker endpoint is reachable yet. Start Docker Engine in WSL and expose it through a local Docker endpoint, then refresh.',
manualUrl: WSL_GUIDE_URL
};
}
async assessDockerDesktop() {
if (await this.#isWindowsServer()) return null;
return await this.#dockerDesktopPath() ? this.#dockerDesktopStoppedAssessment() : null;
}
async provision(options = {}) {
const assessment = await this.assess();
if (assessment?.mode === 'wsl_feature' && assessment.state === 'not_provisioned') {
return await this.#installWslFeatures(options);
}
if (assessment?.mode === 'wsl_distribution' && assessment.state === 'not_provisioned') {
return await this.#installWslDistribution(options);
}
if (assessment?.mode === 'wsl_engine' && assessment.state === 'not_provisioned') {
await this.#installAndStartWslDocker(assessment.distro, options);
return { endpoint: this.endpoint() };
}
if (assessment?.mode === 'wsl_bridge_dependency' && assessment.state === 'not_provisioned') {
await this.#installWslBridgeDependencies(assessment.distro, options);
await this.#configureAndStartWslDocker(assessment.distro);
await this._ensureProxy({ distro: assessment.distro });
return { endpoint: this.endpoint() };
}
if (assessment?.mode === 'wsl_engine' && assessment.state === 'engine_stopped') {
options.onProgress?.('Starting WSL Docker Engine');
await this.#configureAndStartWslDocker(assessment.distro);
await this._ensureProxy({ distro: assessment.distro });
return { endpoint: this.endpoint() };
}
if (assessment?.mode === 'docker_desktop' && assessment.state === 'engine_stopped') {
options.onProgress?.('Starting Docker Desktop');
return await this.#startDockerDesktop(options);
}
throw makeError('RUNTIME_UNSUPPORTED', assessment.detail, this.#manualDetails(assessment));
}
async start(options = {}) {
if (options.mode === 'docker_desktop') {
return await this.#startDockerDesktop(options);
}
const assessment = await this.assess();
if (assessment?.mode === 'wsl_engine') {
options.onProgress?.('Starting WSL Docker Engine');
await this.#configureAndStartWslDocker(assessment.distro);
await this._ensureProxy({ distro: assessment.distro });
return { endpoint: this.endpoint() };
}
if (assessment?.mode === 'docker_desktop') {
options.onProgress?.('Starting Docker Desktop');
return await this.#startDockerDesktop(options);
}
throw makeError('RUNTIME_UNSUPPORTED', assessment.detail, this.#manualDetails(assessment));
}
async status() {
return {
exists: await this.#binaryExists('wsl.exe'),
running: false,
needsRelogin: false
};
}
endpoint() {
return {
kind: 'tcp',
host: '127.0.0.1',
port: 23750,
dockerHost: 'tcp://127.0.0.1:23750'
};
}
async #assessWindowsClient() {
const dockerDesktopPath = await this.#dockerDesktopPath();
const dockerDesktopInstalled = Boolean(dockerDesktopPath);
const wslPresent = await this.#binaryExists('wsl.exe');
if (!wslPresent) {
if (dockerDesktopInstalled) return this.#dockerDesktopStoppedAssessment();
return this.#wslFeatureSetupAssessment('Local Agent Zero runtime Setup may ask for Windows approval and may require a restart.');
}
const distroList = await this.#wslList();
const distro = selectWindowsWslDistro(distroList);
if (!distro) {
const wslUsable = this.#wslListShowsUsableFeatures(distroList);
const wslFeature = await this.#optionalFeatureState('Microsoft-Windows-Subsystem-Linux');
const vmPlatform = await this.#optionalFeatureState('VirtualMachinePlatform');
if (!wslUsable && (wslFeature !== 'Enabled' || vmPlatform !== 'Enabled')) {
if (dockerDesktopInstalled) return this.#dockerDesktopStoppedAssessment();
return this.#wslFeatureSetupAssessment('Local Agent Zero runtime Setup may ask for Windows approval and may require a restart.');
}
if (dockerDesktopInstalled) return this.#dockerDesktopStoppedAssessment();
return {
state: 'not_provisioned',
mode: 'wsl_distribution',
detail: 'Finish local Agent Zero runtime Setup.',
manualCommand: 'wsl.exe --install -d Debian --no-launch',
manualUrl: WSL_INSTALL_URL,
setupActionLabel: 'Setup Agent Zero'
};
}
const hasDocker = await this.#wslCommandOk(distro.name, 'command -v docker >/dev/null 2>&1');
const hasDockerd = await this.#wslCommandOk(distro.name, 'command -v dockerd >/dev/null 2>&1');
if (!hasDocker || !hasDockerd) {
if (dockerDesktopInstalled) return this.#dockerDesktopStoppedAssessment();
return {
state: 'not_provisioned',
mode: 'wsl_engine',
distro: distro.name,
detail: 'Finish local Agent Zero runtime Setup.',
manualUrl: DOCKER_ENGINE_URL,
setupActionLabel: 'Setup Agent Zero'
};
}
const hasPython = await this.#wslCommandOk(distro.name, 'command -v python3 >/dev/null 2>&1');
if (!hasPython) {
return {
state: 'not_provisioned',
mode: 'wsl_bridge_dependency',
distro: distro.name,
detail: 'Finish local Agent Zero runtime Setup.',
manualCommand: 'sudo apt-get update && sudo apt-get install -y python3',
manualUrl: DOCKER_ENGINE_URL,
setupActionLabel: 'Setup Agent Zero'
};
}
const dockerReady = await this.#wslRootCommandOk(distro.name, 'docker info >/dev/null 2>&1');
if (dockerReady) {
return {
state: 'engine_stopped',
mode: 'wsl_engine',
distro: distro.name,
detail: 'Agent Zero local runtime is ready to start.'
};
}
return {
state: 'engine_stopped',
mode: 'wsl_engine',
distro: distro.name,
detail: 'Agent Zero local runtime is installed but needs to be started.'
};
}
#dockerDesktopStoppedAssessment() {
return {
state: 'engine_stopped',
mode: 'docker_desktop',
detail: 'Docker Desktop is installed but not running. Start Docker Desktop, wait until it finishes starting, then return here.'
};
}
#wslFeatureSetupAssessment(detail) {
return {
state: 'not_provisioned',
mode: 'wsl_feature',
detail,
manualCommand: 'wsl.exe --install --no-distribution',
manualUrl: WSL_INSTALL_URL,
requiresAdmin: true,
requiresRestart: true,
setupActionLabel: 'Setup Agent Zero'
};
}
async #binaryExists(binary) {
const result = await this._runCommand('where.exe', [binary], { timeoutMs: 5000 }).catch(() => ({ code: 1 }));
return result.code === 0;
}
async #isWindowsServer() {
if (this._isWindowsServerOverride !== null) return this._isWindowsServerOverride;
const script = '(Get-CimInstance Win32_OperatingSystem).ProductType';
const result = await this.#powershell(script);
const productType = Number(String(result.stdout || '').trim());
return Number.isFinite(productType) && productType !== 1;
}
async #optionalFeatureState(name) {
const safeName = String(name || '').replace(/'/g, "''");
const script = `try { (Get-WindowsOptionalFeature -Online -FeatureName '${safeName}' -ErrorAction Stop).State } catch { 'Unknown' }`;
const result = await this.#powershell(script);
return String(result.stdout || '').trim() || 'Unknown';
}
async #wslList() {
const result = await this._runCommand('wsl.exe', ['-l', '-v'], { timeoutMs: 15000 }).catch((error) => ({
code: -1,
stdout: '',
stderr: error?.message || String(error)
}));
return cleanCommandText(`${result.stdout || ''}\n${result.stderr || ''}`);
}
#wslListShowsUsableFeatures(text) {
const value = String(text || '');
if (/WSL_E_WSL_OPTIONAL_COMPONENT_REQUIRED/i.test(value)) return false;
if (/WSL_E_DEFAULT_DISTRO_NOT_FOUND/i.test(value)) return true;
if (/has no installed distributions|no installed distributions/i.test(value)) return true;
if (/non ha distribuzioni installate/i.test(value)) return true;
if (/^\s*\*?\s*NAME\s+STATE\s+VERSION\b/im.test(value)) return true;
return false;
}
async #wslCommandOk(distro, script) {
const result = await this.#wslSh(distro, script, { timeoutMs: 15000 }).catch(() => ({ code: 1 }));
return result.code === 0;
}
async #wslRootCommandOk(distro, script) {
const result = await this.#wslRootSh(distro, script, { timeoutMs: 15000 }).catch(() => ({ code: 1 }));
return result.code === 0;
}
async #configureAndStartWslDocker(distro) {
const script = [
'set -eu',
'if docker info >/dev/null 2>&1; then exit 0; fi',
'if command -v systemctl >/dev/null 2>&1 && [ "$(cat /proc/1/comm)" = "systemd" ]; then',
' systemctl reset-failed docker || true',
' systemctl start docker || systemctl restart docker',
'elif command -v service >/dev/null 2>&1; then',
' service docker start || service docker restart',
'else',
' dockerd >/tmp/a0-dockerd.log 2>&1 &',
'fi',
'for attempt in $(seq 1 30); do',
' if docker info >/dev/null 2>&1; then exit 0; fi',
' sleep 1',
'done',
'docker info >/dev/null'
].join('\n');
const result = await this.#wslRootSh(distro, script, { timeoutMs: 120000 });
if (result.code !== 0) {
throw makeError('RUNTIME_START_FAILED', 'Could not start Docker Engine inside WSL.', {
distro,
exitCode: result.code,
stdout: cleanCommandText(result.stdout),
stderr: cleanCommandText(result.stderr)
});
}
}
async #installWslFeatures(options = {}) {
options.onProgress?.('Requesting Windows approval');
const script = [
'$ErrorActionPreference = "Continue"',
'wsl.exe --install --no-distribution 2>&1 | Tee-Object -FilePath $setupLog -Append -ErrorAction Stop',
'if ($LASTEXITCODE -ne 0) { wsl.exe --install --no-distribution --web-download 2>&1 | Tee-Object -FilePath $setupLog -Append -ErrorAction Stop }',
'if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }',
'wsl.exe --set-default-version 2 2>&1 | Tee-Object -FilePath $setupLog -Append -ErrorAction Stop',
'exit $LASTEXITCODE'
].join('\n');
await this.#runElevatedPowerShell(script, {
timeoutMs: options.timeoutMs || 20 * 60 * 1000,
signal: options.signal,
onProgress: options.onProgress
});
return {
state: 'needs_followup',
detail: 'Agent Zero Setup was started. Restart Windows if prompted, then return here to continue.'
};
}
async #installWslDistribution(options = {}) {
options.onProgress?.('Installing Debian');
const existing = await fs.stat(this.wslInstallDir).catch((error) => {
if (error.code === 'ENOENT') return null;
throw error;
});
if (existing) {
throw makeError('RUNTIME_PROVISION_FAILED', 'The Agent Zero WSL runtime folder already exists. Preserve or move that folder before retrying.', { path: this.wslInstallDir });
}
const rootfs = await this.prepareDebianRootfs(options);
options.onProgress?.('Preparing Debian');
await fs.mkdir(path.dirname(this.wslInstallDir), { recursive: true });
const result = await this._runCommand('wsl.exe', [
'--import', MANAGED_WSL_DISTRO, this.wslInstallDir, rootfs, '--version', '2'
], { timeoutMs: options.timeoutMs || 20 * 60 * 1000, signal: options.signal });
if (result.code !== 0) {
throw makeError('RUNTIME_PROVISION_FAILED', 'Could not import Debian for WSL.', {
exitCode: result.code,
stdout: cleanCommandText(result.stdout),
stderr: cleanCommandText(result.stderr)
});
}
await this.#installAndStartWslDocker(MANAGED_WSL_DISTRO, { ...options, freshDistribution: true });
return { endpoint: this.endpoint() };
}
async prepareDebianRootfs(options = {}) {
const arch = process.arch === 'arm64' || /^arm64$/i.test(process.env.PROCESSOR_ARCHITEW6432 || process.env.PROCESSOR_ARCHITECTURE || '') ? 'arm64' : 'amd64';
const rootfs = path.join(this.managedDir, `debian-trixie-slim-${arch}.rootfs.tar.gz`);
let lastProgress = -1;
await new DockerHubRegistry().downloadPublicBlob('library/debian', DEBIAN_ROOTFS[arch], rootfs, {
signal: options.signal,
onProgress: (_message, progress) => {
if (progress === lastProgress) return;
lastProgress = progress;
options.onProgress?.('Installing Debian', progress);
}
});
return rootfs;
}
async #installAndStartWslDocker(distro, options = {}) {
options.onProgress?.('Installing Docker Engine');
await this.#installDockerEngineInWsl(distro, options);
options.onProgress?.('Starting WSL Docker Engine');
if (options.freshDistribution) {
// WSL reads the new systemd setting on the next boot of this distro.
const result = await this._runCommand('wsl.exe', ['--terminate', distro], {
timeoutMs: 30000,
signal: options.signal
});
if (result.code !== 0) {
throw makeError('RUNTIME_START_FAILED', 'Could not restart the Agent Zero WSL runtime.', {
distro,
exitCode: result.code,
stdout: cleanCommandText(result.stdout),
stderr: cleanCommandText(result.stderr)
});
}
}
await this.#configureAndStartWslDocker(distro);
options.onProgress?.('Starting local Docker bridge');
await this._ensureProxy({ distro });
}
async #installDockerEngineInWsl(distro, options = {}) {
const managed = options.freshDistribution || (distro === MANAGED_WSL_DISTRO
&& (await fs.stat(path.join(this.wslInstallDir, 'ext4.vhdx')).catch(() => null))?.isFile());
const recommends = managed ? '--no-install-recommends ' : '';
const script = [
'set -eu',
'export DEBIAN_FRONTEND=noninteractive',
'. /etc/os-release',
'case "${ID:-}" in',
' debian) docker_distro=debian; codename="${VERSION_CODENAME:-}" ;;',
' *) docker_distro=ubuntu; codename="${UBUNTU_CODENAME:-${VERSION_CODENAME:-}}" ;;',
'esac',
'if [ -z "$codename" ]; then echo "Could not determine Linux distribution codename" >&2; exit 1; fi',
'apt-get update',
...(managed ? ['apt-get upgrade -y --no-install-recommends'] : []),
`apt-get install -y ${recommends}ca-certificates curl python3${managed ? ' procps systemd-sysv' : ''}`,
...(managed ? ["printf '[boot]\\nsystemd=true\\n' >/etc/wsl.conf"] : []),
'for pkg in docker.io docker-compose docker-compose-v2 docker-doc podman-docker containerd runc; do apt-get remove -y "$pkg" >/dev/null 2>&1 || true; done',
'install -m 0755 -d /etc/apt/keyrings',
'curl -fsSL "https://download.docker.com/linux/$docker_distro/gpg" -o /etc/apt/keyrings/docker.asc',
'chmod a+r /etc/apt/keyrings/docker.asc',
'arch="$(dpkg --print-architecture)"',
'cat > /etc/apt/sources.list.d/docker.sources <<EOF',
'Types: deb',
'URIs: https://download.docker.com/linux/${docker_distro}',
'Suites: ${codename}',
'Components: stable',
'Architectures: ${arch}',
'Signed-By: /etc/apt/keyrings/docker.asc',
'EOF',
'apt-get update',
`apt-get install -y ${recommends}docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin`,
...(managed ? ['systemctl enable docker.service', 'apt-get clean'] : [])
].join('\n');
const result = await this.#wslRootSh(distro, script, {
timeoutMs: options.timeoutMs || (managed ? 40 : 20) * 60 * 1000,
signal: options.signal
});
if (result.code !== 0) {
throw makeError('RUNTIME_PROVISION_FAILED', 'Could not install Docker Engine inside WSL.', {
distro,
exitCode: result.code,
stdout: cleanCommandText(result.stdout),
stderr: cleanCommandText(result.stderr)
});
}
}
async #installWslBridgeDependencies(distro, options = {}) {
options.onProgress?.('Installing bridge dependency');
const result = await this.#wslRootSh(distro, 'set -eu\nexport DEBIAN_FRONTEND=noninteractive\napt-get update\napt-get install -y python3', {
timeoutMs: options.timeoutMs || 10 * 60 * 1000,
signal: options.signal
});
if (result.code !== 0) {
throw makeError('RUNTIME_PROVISION_FAILED', 'Could not install WSL bridge dependencies.', {
distro,
exitCode: result.code,
stdout: cleanCommandText(result.stdout),
stderr: cleanCommandText(result.stderr)
});
}
return {
state: 'needs_followup',
detail: 'Agent Zero Setup is almost done. Continue Setup to start the local runtime.'
};
}
async #dockerDesktopPath() {
const script = [
'$paths = @(',
' (Join-Path $env:ProgramFiles "Docker\\Docker\\Docker Desktop.exe")',
')',
'if (${env:ProgramFiles(x86)}) { $paths += (Join-Path ${env:ProgramFiles(x86)} "Docker\\Docker\\Docker Desktop.exe") }',
'if ($env:LOCALAPPDATA) { $paths += (Join-Path $env:LOCALAPPDATA "Programs\\DockerDesktop\\Docker Desktop.exe") }',
'$found = $paths | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1',
'if ($found) { $found }'
].join('; ');
const result = await this.#powershell(script).catch(() => ({ code: 1, stdout: '' }));
return result.code === 0 ? String(result.stdout || '').trim() : '';
}
async #startDockerDesktop(options = {}) {
const desktopPath = await this.#dockerDesktopPath();
const command = desktopPath
? `Start-Process -FilePath '${desktopPath.replace(/'/g, "''")}' -WindowStyle Hidden -ErrorAction Stop`
: "Start-Process -FilePath 'docker-desktop:' -WindowStyle Hidden -ErrorAction Stop";
const result = await this.#powershell(command, { signal: options.signal });
if (result.code !== 0) {
throw makeError('RUNTIME_START_FAILED', 'Could not start Docker Desktop.', {
exitCode: result.code,
stdout: cleanCommandText(result.stdout),
stderr: cleanCommandText(result.stderr)
});
}
options.onProgress?.('Waiting for Docker Desktop');
const ready = await this.#waitForDockerDesktop(options.signal);
if (!ready) {
throw makeError('RUNTIME_START_FAILED', 'Docker Desktop started, but Docker did not become reachable.');
}
return { endpoint: { kind: 'npipe', dockerHost: 'npipe:////./pipe/docker_engine' } };
}
async #waitForDockerDesktop(signal, timeoutMs = 120000) {
const { DockerInterface } = await import('../DockerInterface.mjs');
const startedAt = Date.now();
while (Date.now() - startedAt < timeoutMs) {
if (signal?.aborted) throw makeError('ABORTED', 'Runtime start aborted');
const env = await DockerInterface.detectEnvironment({
dockerHost: 'npipe:////./pipe/docker_engine',
candidateHosts: [],
discoverDockerContexts: false,
enableWindowsWslProxy: false,
timeoutMs: 1500
});
if (env.dockerAvailable) return true;
await sleep(1000);
}
return false;
}
async #runElevatedPowerShell(script, options = {}) {
const setupDir = await fs.mkdtemp(path.join(os.tmpdir(), 'a0-wsl-setup-'));
const scriptPath = path.join(setupDir, 'setup.ps1');
const logPath = path.join(setupDir, 'setup.log');
let timedOut = false;
try {
await fs.writeFile(scriptPath, '\uFEFF' + [
`$setupLog = '${logPath.replace(/'/g, "''")}'`,
'try {',
script,
'} catch {',
' $_ | Out-String | Tee-Object -FilePath $setupLog -Append',
' exit 1',
'}'
].join('\n'), 'utf8');
const launcher = [
'$ErrorActionPreference = "Stop"',
`$argsList = @('-NoLogo', '-NoProfile', '-ExecutionPolicy', 'RemoteSigned', '-File', '"${scriptPath.replace(/'/g, "''")}"')`,
'$p = Start-Process -FilePath "powershell.exe" -ArgumentList $argsList -Verb RunAs -WindowStyle Normal -PassThru',
'$null = $p.Handle',
'Write-Output "A0_WSL_SETUP_STARTED"',
'$p.WaitForExit()',
'exit $p.ExitCode'
].join('; ');
const result = await this.#powershell(launcher, {
timeoutMs: options.timeoutMs || 20 * 60 * 1000,
signal: options.signal,
onLine: (line) => {
if (line === 'A0_WSL_SETUP_STARTED') options.onProgress?.('Enabling WSL features');
}
});
if (result.code !== 0) {
throw makeError('RUNTIME_PROVISION_FAILED', 'Windows WSL Setup did not complete.', {
exitCode: result.code,
stdout: cleanCommandText(result.stdout),
stderr: cleanCommandText(result.stderr)
});
}
} catch (error) {
timedOut = error?.code === 'TIMEOUT';
const buffer = await fs.readFile(logPath).catch(() => Buffer.alloc(0));
const output = buffer.toString(buffer[0] === 0xff && buffer[1] === 0xfe ? 'utf16le' : 'utf8').replace(/^\uFEFF/, '').trim();
const detail = tail(output || error?.details?.stderr || error?.message, 1200).trim();
const message = timedOut
? 'Windows WSL Setup timed out. Check the Windows setup window before retrying.'
: 'Windows WSL Setup did not complete.';
throw makeError('RUNTIME_PROVISION_FAILED', detail ? `${message}\n${detail}` : message, error?.details);
} finally {
if (!timedOut) await fs.rm(setupDir, { recursive: true, force: true }).catch(() => {});
}
}
async #wslSh(distro, script, options = {}) {
const args = [];
const selected = String(distro || '').trim();
if (selected) args.push('-d', selected);
args.push('--exec', 'sh', '-lc', script);
return await this._runCommand('wsl.exe', args, { timeoutMs: options.timeoutMs || 15000, signal: options.signal });
}
async #wslRootSh(distro, script, options = {}) {
const args = [];
const selected = String(distro || '').trim();
if (selected) args.push('-d', selected);
args.push('-u', 'root', '--exec', 'sh', '-lc', script);
return await this._runCommand('wsl.exe', args, { timeoutMs: options.timeoutMs || 120000, signal: options.signal });
}
#manualDetails(assessment) {
return {
manualUrl: assessment?.manualUrl,
manualCommand: assessment?.manualCommand,
distro: assessment?.distro
};
}
async #powershell(script, options = {}) {
return await this._runCommand(
'powershell.exe',
['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script],
{ timeoutMs: options.timeoutMs || 15000, signal: options.signal, onLine: options.onLine }
);
}
}
export const WINDOWS_WSL_GUIDE_URL = WSL_GUIDE_URL;
export const WINDOWS_DOCKER_DESKTOP_URL = DOCKER_DESKTOP_URL;
function cleanCommandText(value) {
return String(value || '').replace(/\0/g, '');
}