Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Windows packaging: extract the CUA Driver with System32 tar; say why a driver gives no version (#6657)
Milind Soni0af84856e0c7
diff --git a/scripts/cua-binary-version.mjs b/scripts/cua-binary-version.mjsnew file mode 100644index 0000000000..632f435a85--- /dev/null+++ b/scripts/cua-binary-version.mjs@@ -0,0 +1,103 @@+// Ask a CUA Driver executable for its version, and say exactly what happened when it does not give one: the+// packaging scripts used to turn every failure (a start Windows refused, a crash, a timeout, other output) into+// "does not report version", which hid the cause. The sha256 pin stays the integrity check; this only reports.+import { execFile } from "node:child_process";+import { existsSync, readdirSync, statSync } from "node:fs";+import { release, version as osVersion } from "node:os";+import { join } from "node:path";++const OUTPUT_SHOWN = 2_000;++/** Windows NTSTATUS exit codes a process that never ran its own code ends with. */+const NTSTATUS = {+ 0xc0000005: "STATUS_ACCESS_VIOLATION: it crashed",+ 0xc000007b: "STATUS_INVALID_IMAGE_FORMAT: a wrong-architecture or damaged executable or DLL",+ 0xc0000135: "STATUS_DLL_NOT_FOUND: a DLL it needs is missing",+ 0xc0000139: "STATUS_ENTRYPOINT_NOT_FOUND: a DLL it loads lacks a function it needs",+ 0xc0000142: "STATUS_DLL_INIT_FAILED: a DLL it loads failed to start",+ 0xc0000409: "STATUS_STACK_BUFFER_OVERRUN: it ended itself on a fatal error (fail fast or abort)",+ 0xc0000374: "STATUS_HEAP_CORRUPTION: it crashed",+ 0xc000001d: "STATUS_ILLEGAL_INSTRUCTION: it uses an instruction this CPU lacks",+};++/** An exit code as Windows means it: a large one is an NTSTATUS, shown in hex with what it stands for. */+export function describeExitCode(code) {+ const unsigned = code >>> 0;+ if (unsigned < 0x80000000) return String(code);+ const hex = `0x${unsigned.toString(16).toUpperCase().padStart(8, "0")}`;+ const meaning = NTSTATUS[unsigned];+ return `${unsigned} (${hex}${meaning ? `, ${meaning}` : ""})`;+}++const shown = (text) => {+ const trimmed = String(text ?? "").trim();+ return JSON.stringify(trimmed.length > OUTPUT_SHOWN ? `${trimmed.slice(0, OUTPUT_SHOWN)}…` : trimmed);+};++/** What one `--version` run did, in a line: started or not, how it ended, and everything it printed. */+export function describeRun({ error, stdout, stderr, elapsedMs }, timeoutMs) {+ let ended;+ if (!error) ended = "exited with code 0";+ else if (error.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") ended = "printed more than 256 KiB and was ended";+ else if (error.killed && (error.signal || error.code === null)) ended = `timed out after ${timeoutMs} ms and was ended with ${error.signal ?? "a kill"}`;+ else if (typeof error.code === "string") ended = `could not run: ${error.code}${error.syscall ? ` (${error.syscall})` : ""}${error.errno !== undefined ? ` errno ${error.errno}` : ""}`;+ else if (typeof error.code === "number") ended = `exited with code ${describeExitCode(error.code)}`;+ else if (error.signal) ended = `was ended by ${error.signal}`;+ else ended = `failed: ${error.message}`;+ return `${ended} after ${elapsedMs} ms; stdout ${shown(stdout)}; stderr ${shown(stderr)}`;+}++const VERSION = /cua-driver\s+([\d.]+)/;++function runOnce(binary, { timeoutMs, env }) {+ const started = Date.now();+ return new Promise((resolve) => {+ execFile(binary, ["--version"], {+ encoding: "utf8", timeout: timeoutMs, maxBuffer: 256 * 1024, windowsHide: true, ...(env ? { env } : {}),+ }, (error, stdout, stderr) => resolve({ error, stdout, stderr, elapsedMs: Date.now() - started }));+ });+}++/**+ * Runs `<binary> --version` until it reports a version, a few times with a short wait between (a freshly written+ * executable can be held by a scan on its first start). Returns the version, or null with `why`: every attempt, said.+ */+export async function probeCuaVersion(binary, { attempts = 3, timeoutMs = 20_000, retryWaitMs = 2_000, env, run = runOnce, sleep } = {}) {+ if (!binary) return { version: null, why: "no executable was named" };+ if (!existsSync(binary)) return { version: null, why: `${binary} does not exist` };+ const wait = sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));+ const tries = [];+ for (let attempt = 1; attempt <= attempts; attempt++) {+ const result = await run(binary, { timeoutMs, env });+ const version = result.error ? null : String(result.stdout ?? "").match(VERSION)?.[1] ?? null;+ if (version) {+ if (attempt > 1) console.log(`${binary} reported its version on attempt ${attempt}; before that it ${tries.join("; then it ")}`);+ return { version, why: null };+ }+ tries.push(describeRun(result, timeoutMs));+ if (attempt < attempts) await wait(retryWaitMs);+ }+ return { version: null, why: `\`${binary} --version\` gave no version in ${attempts} attempts: it ${tries.map((line, index) => `(${index + 1}) ${line}`).join("; ")}` };+}++/** The facts about this Windows machine and the extracted release that decide whether its executable can start. */+export function windowsRunnerFacts(folder) {+ const system32 = join(process.env.SystemRoot ?? "C:\\Windows", "System32");+ const runtimes = ["VCRUNTIME140.dll", "VCRUNTIME140_1.dll", "MSVCP140.dll", "d3d11.dll", "dwmapi.dll", "oleacc.dll", "wtsapi32.dll"]+ .map((dll) => `${dll} ${existsSync(join(system32, dll)) ? "present" : "MISSING"}`);+ let files;+ try {+ files = readdirSync(folder).map((name) => {+ const path = join(folder, name);+ const marked = existsSync(`${path}:Zone.Identifier`) ? " (has a Zone.Identifier mark)" : "";+ return `${name} ${statSync(path).size} bytes${marked}`;+ });+ } catch (error) {+ files = [`(could not list ${folder}: ${error instanceof Error ? error.message : String(error)})`];+ }+ return [+ `Windows ${release()} (${osVersion()}), node ${process.version} ${process.arch}`,+ `System32 DLLs: ${runtimes.join(", ")}`,+ `${folder}: ${files.join(", ")}`,+ ].join("\n");+}diff --git a/scripts/cua-binary-version.test.mjs b/scripts/cua-binary-version.test.mjsnew file mode 100644index 0000000000..64d4b4e6c9--- /dev/null+++ b/scripts/cua-binary-version.test.mjs@@ -0,0 +1,59 @@+import { describe, expect, it } from "vitest";+import { describeExitCode, describeRun, probeCuaVersion } from "./cua-binary-version.mjs";++const failure = (fields) => Object.assign(new Error("Command failed"), fields);++describe("a CUA Driver that gives no version is described as it failed", () => {+ it("names a Windows NTSTATUS exit in hex with what it means, and leaves an ordinary exit code as it is", () => {+ expect(describeExitCode(3221225781)).toBe("3221225781 (0xC0000135, STATUS_DLL_NOT_FOUND: a DLL it needs is missing)");+ expect(describeExitCode(-1073741515)).toContain("0xC0000135");+ expect(describeExitCode(3221225477)).toContain("0xC0000005, STATUS_ACCESS_VIOLATION");+ expect(describeExitCode(3221226505)).toContain("0xC0000409");+ expect(describeExitCode(2)).toBe("2");+ });++ it("tells a refused start, a timeout, a crash and a clean exit with other output apart, with what each printed", () => {+ expect(describeRun({ error: failure({ code: "EACCES", syscall: "spawn C:\\cua-driver.exe", errno: -4092 }), stdout: "", stderr: "", elapsedMs: 3 }, 20_000))+ .toBe('could not run: EACCES (spawn C:\\cua-driver.exe) errno -4092 after 3 ms; stdout ""; stderr ""');+ expect(describeRun({ error: failure({ killed: true, signal: "SIGTERM", code: null }), stdout: "", stderr: "", elapsedMs: 20_004 }, 20_000))+ .toMatch(/^timed out after 20000 ms and was ended with SIGTERM/);+ expect(describeRun({ error: failure({ code: 3221225781 }), stdout: "", stderr: "", elapsedMs: 40 }, 20_000))+ .toMatch(/^exited with code 3221225781 \(0xC0000135, STATUS_DLL_NOT_FOUND/);+ expect(describeRun({ error: failure({ code: 1 }), stdout: "", stderr: "panicked at src/main.rs", elapsedMs: 9 }, 20_000))+ .toBe('exited with code 1 after 9 ms; stdout ""; stderr "panicked at src/main.rs"');+ expect(describeRun({ error: null, stdout: "cua-driver-rs 0.45.4\n", stderr: "", elapsedMs: 7 }, 20_000))+ .toBe('exited with code 0 after 7 ms; stdout "cua-driver-rs 0.45.4"; stderr ""');+ });+});++describe("asking a CUA Driver for its version", () => {+ it("tries again after a short wait when the first start fails, and takes the version the next one reports", async () => {+ const results = [{ error: failure({ code: "EBUSY", syscall: "spawn" }), stdout: "", stderr: "", elapsedMs: 1 }, { error: null, stdout: "cua-driver 0.45.4\n", stderr: "", elapsedMs: 1 }];+ const waits = [];+ const probe = await probeCuaVersion(process.execPath, { run: async () => results.shift(), sleep: async (ms) => { waits.push(ms); } });+ expect(probe).toEqual({ version: "0.45.4", why: null });+ expect(waits).toEqual([2_000]);+ });++ it("says every attempt when none gives a version", async () => {+ let runs = 0;+ const probe = await probeCuaVersion(process.execPath, {+ attempts: 2, run: async () => { runs++; return { error: failure({ code: 3221225781 }), stdout: "", stderr: "", elapsedMs: 5 }; }, sleep: async () => {},+ });+ expect(runs).toBe(2);+ expect(probe.version).toBeNull();+ expect(probe.why).toMatch(/gave no version in 2 attempts: it \(1\) exited with code 3221225781 \(0xC0000135.*\(2\) exited with code 3221225781/);+ });++ it("says a missing executable is missing, without running anything", async () => {+ const probe = await probeCuaVersion("/nowhere/cua-driver", { run: async () => { throw new Error("ran"); } });+ expect(probe).toEqual({ version: null, why: "/nowhere/cua-driver does not exist" });+ });++ it("reports what a real executable printed when it is not a CUA Driver", async () => {+ const probe = await probeCuaVersion(process.execPath, { attempts: 1 });+ expect(probe.version).toBeNull();+ expect(probe.why).toContain(`exited with code 0`);+ expect(probe.why).toContain(`stdout ${JSON.stringify(process.version)}`);+ });+});diff --git a/scripts/cua-linux-release.mjs b/scripts/cua-linux-release.mjsindex 946d63429c..6996529f45 100644--- a/scripts/cua-linux-release.mjs+++ b/scripts/cua-linux-release.mjs@@ -365,8 +365,9 @@ async function validateStagedRuntime(stageDirectory, { licenseDirectory }) {const actual = await readFile(path.join(licensesDirectory, name));if (!actual.equals(expected)) throw new Error(`staged CUA license resource mismatch: ${name}`);}- if ((await binaryVersion(path.join(stageDirectory, "cua-driver"))) !== `cua-driver ${LINUX_CUA_RELEASE.version}`) {- throw new Error(`staged CUA Driver does not report version ${LINUX_CUA_RELEASE.version}`);+ const reportedVersion = await binaryVersion(path.join(stageDirectory, "cua-driver"));+ if (reportedVersion !== `cua-driver ${LINUX_CUA_RELEASE.version}`) {+ throw new Error(`staged CUA Driver does not report version ${LINUX_CUA_RELEASE.version}: its --version printed ${JSON.stringify(reportedVersion.slice(0, 2_000))}`);}await validateBinaryManifest(path.join(stageDirectory, "cua-driver"));return manifest;diff --git a/scripts/prepare-cua-win.mjs b/scripts/prepare-cua-win.mjsindex 79d0a8a4c5..666c966439 100644--- a/scripts/prepare-cua-win.mjs+++ b/scripts/prepare-cua-win.mjs@@ -7,6 +7,7 @@ import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";import { promisify } from "node:util";import { build } from "esbuild";+import { probeCuaVersion, windowsRunnerFacts } from "./cua-binary-version.mjs";import { createBackgroundExecutable } from "./cua-windows-background.mjs";if (process.platform !== "win32" || process.arch !== "x64") throw new Error("prepare-cua-win requires Windows x64");@@ -32,20 +33,13 @@ if (expectedVersion !== release.version) {);}-async function binaryVersion(candidate) {- if (!candidate || !existsSync(candidate)) return null;- try {- const { stdout } = await run(candidate, ["--version"], { timeout: 5000, windowsHide: true });- return stdout.match(/cua-driver\s+([\d.]+)/)?.[1] ?? null;- } catch {- return null;- }-}+/** What the executable says, or why it says nothing (`why`), in the words of the failure itself. */+const reported = ({ version, why }) => (version ? `it reports ${version}` : why);async function officialBinary() {const cache = join(root, "node_modules", ".cache", "openmausbot", `cua-driver-${release.version}-win`);const cachedBinary = join(cache, "cua-driver.exe");- if ((await binaryVersion(cachedBinary)) === expectedVersion) return cachedBinary;+ if (existsSync(cachedBinary) && (await probeCuaVersion(cachedBinary, { attempts: 1 })).version === expectedVersion) return cachedBinary;await rm(cache, { recursive: true, force: true });await mkdir(cache, { recursive: true });@@ -63,25 +57,33 @@ async function officialBinary() {}const archive = join(cache, release.file);await writeFile(archive, bytes);- await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command",- "Expand-Archive -LiteralPath $env:OMB_CUA_ARCHIVE -DestinationPath $env:OMB_CUA_EXTRACT"], {- env: { ...process.env, OMB_CUA_ARCHIVE: archive, OMB_CUA_EXTRACT: cache },- timeout: 60_000,- windowsHide: true,- });- if ((await binaryVersion(cachedBinary)) !== expectedVersion) {- throw new Error(`downloaded CUA Driver does not report version ${expectedVersion}`);+ // Windows' own bsdtar reads zip archives, and says so when it cannot. PowerShell's Expand-Archive, run from here,+ // exited 0 on the windows-2025 runner image of 2026-11-16 while extracting nothing; the Git tar first on a runner's+ // PATH cannot read zip, hence the full path.+ const tar = join(process.env.SystemRoot ?? "C:\\Windows", "System32", "tar.exe");+ try {+ await run(tar, ["-xf", archive, "-C", cache], { timeout: 120_000, windowsHide: true });+ } catch (error) {+ console.error(windowsRunnerFacts(cache));+ throw new Error(`extracting ${release.file} with ${tar} failed: ${error instanceof Error ? error.message : String(error)}`);+ }+ if (!existsSync(cachedBinary)) {+ console.error(windowsRunnerFacts(cache));+ throw new Error(`extracting ${release.file} with ${tar} exited 0 but left no cua-driver.exe in ${cache}`);+ }+ const probe = await probeCuaVersion(cachedBinary);+ if (probe.version !== expectedVersion) {+ console.error(windowsRunnerFacts(cache));+ throw new Error(`downloaded CUA Driver passed its sha256 check but did not report version ${expectedVersion}: ${reported(probe)}`);}return cachedBinary;}let binary;if (process.env.CUA_DRIVER_PATH) {- const suppliedVersion = await binaryVersion(process.env.CUA_DRIVER_PATH);- if (suppliedVersion !== expectedVersion) {- throw new Error(- `CUA_DRIVER_PATH must point to cua-driver ${expectedVersion}; found ${suppliedVersion ?? "an unreadable binary"}`,- );+ const supplied = await probeCuaVersion(process.env.CUA_DRIVER_PATH);+ if (supplied.version !== expectedVersion) {+ throw new Error(`CUA_DRIVER_PATH must point to cua-driver ${expectedVersion}; ${reported(supplied)}`);}binary = process.env.CUA_DRIVER_PATH;} else {@@ -99,8 +101,9 @@ if (process.env.CUA_DRIVER_PATH) {}}-if ((await binaryVersion(binary)) !== expectedVersion) {- throw new Error(`CUA executable must match SDK ${expectedVersion}`);+const staged = await probeCuaVersion(binary);+if (staged.version !== expectedVersion) {+ throw new Error(`CUA executable must match SDK ${expectedVersion}: ${reported(staged)}`);}const details = await stat(binary);if (!details.isFile()) {diff --git a/scripts/prepare-cua.mjs b/scripts/prepare-cua.mjsindex 82356de98b..b092b3dee3 100644--- a/scripts/prepare-cua.mjs+++ b/scripts/prepare-cua.mjs@@ -10,6 +10,7 @@ import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";import { promisify } from "node:util";import { build } from "esbuild";+import { probeCuaVersion } from "./cua-binary-version.mjs";import { resolveCuaMacArches } from "./cua-mac-arches.mjs";import { LIPO_ARCH, writeThinMachO } from "./mac-thin.mjs";@@ -34,20 +35,13 @@ if (expectedVersion !== release.version) {);}-async function binaryVersion(candidate) {- if (!candidate || !existsSync(candidate)) return null;- try {- const { stdout } = await run(candidate, ["--version"], { timeout: 5000 });- return stdout.match(/cua-driver\s+([\d.]+)/)?.[1] ?? null;- } catch {- return null;- }-}+/** What the executable says, or why it says nothing (`why`), in the words of the failure itself. */+const reported = ({ version, why }) => (version ? `it reports ${version}` : why);async function officialBinary() {const cache = join(root, "node_modules", ".cache", "openmausbot", `cua-driver-${release.version}`);const cachedBinary = join(cache, "cua-driver");- if ((await binaryVersion(cachedBinary)) === expectedVersion) return cachedBinary;+ if (existsSync(cachedBinary) && (await probeCuaVersion(cachedBinary, { attempts: 1 })).version === expectedVersion) return cachedBinary;await rm(cache, { recursive: true, force: true });await mkdir(cache, { recursive: true });@@ -64,19 +58,18 @@ async function officialBinary() {await writeFile(archive, bytes);await run("/usr/bin/tar", ["-xzf", archive, "-C", cache, "cua-driver"]);await chmod(cachedBinary, 0o755);- if ((await binaryVersion(cachedBinary)) !== expectedVersion) {- throw new Error(`downloaded CUA Driver does not report version ${expectedVersion}`);+ const probe = await probeCuaVersion(cachedBinary);+ if (probe.version !== expectedVersion) {+ throw new Error(`downloaded CUA Driver passed its sha256 check but did not report version ${expectedVersion}: ${reported(probe)}`);}return cachedBinary;}let binary;if (process.env.CUA_DRIVER_PATH) {- const suppliedVersion = await binaryVersion(process.env.CUA_DRIVER_PATH);- if (suppliedVersion !== expectedVersion) {- throw new Error(- `CUA_DRIVER_PATH must point to cua-driver ${expectedVersion}; found ${suppliedVersion ?? "an unreadable binary"}`,- );+ const supplied = await probeCuaVersion(process.env.CUA_DRIVER_PATH);+ if (supplied.version !== expectedVersion) {+ throw new Error(`CUA_DRIVER_PATH must point to cua-driver ${expectedVersion}; ${reported(supplied)}`);}binary = process.env.CUA_DRIVER_PATH;} else {@@ -92,7 +85,7 @@ if (process.env.CUA_DRIVER_PATH) {}};binary =- (await binaryVersion(installed)) === expectedVersion && (await installedUniversal())+ existsSync(installed) && (await probeCuaVersion(installed, { attempts: 1 })).version === expectedVersion && (await installedUniversal())? installed: await officialBinary();}