diff --git a/src/agent-device/host/agent-device-supervisor.test.ts b/src/agent-device/host/agent-device-supervisor.test.ts index 53ce93795..dcbbad17b 100644 --- a/src/agent-device/host/agent-device-supervisor.test.ts +++ b/src/agent-device/host/agent-device-supervisor.test.ts @@ -189,6 +189,7 @@ async function arrange(options: Options = {}) { filesystem, healthProbe: health, home: simlockHome, + hostPlatform: "linux", ...supervisorRole(options), leaseMaxTtlMs: options.leaseMaxTtlMs ?? 4 * 60 * 60_000, logger, diff --git a/src/agent-device/host/agent-device-supervisor.ts b/src/agent-device/host/agent-device-supervisor.ts index 55862da36..476a1c22d 100644 --- a/src/agent-device/host/agent-device-supervisor.ts +++ b/src/agent-device/host/agent-device-supervisor.ts @@ -24,7 +24,7 @@ import { NO_ANDROID_DEVICE_SERIAL, } from "../shared/daemon-environment.js"; import type { AgentDeviceHealthProbe } from "./health.js"; -import { findAgentDevice } from "./install.js"; +import { findAgentDevice, pathVariableOf } from "./install.js"; export type AgentDevicePlatform = "ios" | "android"; @@ -90,6 +90,7 @@ export interface AgentDeviceSupervisorOptions { readonly filesystem: Filesystem; readonly healthProbe: AgentDeviceHealthProbe; readonly home: string; + readonly hostPlatform: NodeJS.Platform; readonly ios?: AgentDeviceIosSigning; readonly leaseMaxTtlMs: number; readonly logger: Logger; @@ -324,7 +325,8 @@ export class AgentDeviceSupervisor { const install = await findAgentDevice( o.filesystem, o.config.command, - o.baseEnvironment["PATH"], + pathVariableOf(o.baseEnvironment), + o.hostPlatform, ); if (!install.ok) { this.#fail(install.reason, install.message); diff --git a/src/agent-device/host/install.test.ts b/src/agent-device/host/install.test.ts new file mode 100644 index 000000000..a8e26ef60 --- /dev/null +++ b/src/agent-device/host/install.test.ts @@ -0,0 +1,180 @@ +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { MemoryFilesystem, NodeFilesystem } from "../../ports/index.js"; +import { findAgentDevice, pathVariableOf } from "./install.js"; + +const npm = "/Users/me/AppData/Roaming/npm"; +const packageRoot = `${npm}/node_modules/agent-device`; + +/** why: npm on Windows lays out a global install as a `.cmd` shim beside `node_modules`, every file 0o666. */ +async function windowsNpmInstall( + options: { readonly bin?: unknown; readonly shim?: boolean } = {}, +): Promise { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp(`${packageRoot}/bin`); + await filesystem.mkdirp(`${packageRoot}/dist/src/internal`); + if (options.shim !== false) + await filesystem.writeFileAtomic(`${npm}/agent-device.cmd`, "@node ..."); + await filesystem.writeFileAtomic( + `${packageRoot}/package.json`, + JSON.stringify({ + bin: options.bin ?? { "agent-device": "bin/agent-device.mjs" }, + name: "agent-device", + }), + ); + await filesystem.writeFileAtomic(`${packageRoot}/bin/agent-device.mjs`, "#!/usr/bin/env node\n"); + await filesystem.writeFileAtomic(`${packageRoot}/dist/src/internal/daemon.js`, ""); + for (const path of [`${npm}/agent-device.cmd`, `${packageRoot}/bin/agent-device.mjs`]) { + if (await filesystem.exists(path)) filesystem.defineAttributes(path, { mode: 0o666 }); + } + return filesystem; +} + +// why: pure lookup rules, per platform, with many cases the supervisor's own tests reach only one at a time. +describe("findAgentDevice", () => { + it.each([ + ["an object", { "agent-device": "bin/agent-device.mjs" }], + ["a string", "./bin/agent-device.mjs"], + ])( + "finds an npm .cmd shim on a Windows PATH and stands in its package's bin, named as %s", + async (_form, bin) => { + const filesystem = await windowsNpmInstall({ bin }); + + await expect( + findAgentDevice(filesystem, "agent-device", `/Windows/System32;${npm};/other`, "win32"), + ).resolves.toEqual({ + entry: `${packageRoot}/dist/src/internal/daemon.js`, + ok: true, + realPath: `${packageRoot}/bin/agent-device.mjs`, + }); + }, + ); + + it("finds a local install's shim in node_modules/.bin, its package beside .bin", async () => { + const project = "/work/app/node_modules"; + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp(`${project}/.bin`); + await filesystem.mkdirp(`${project}/agent-device/bin`); + await filesystem.mkdirp(`${project}/agent-device/dist/src`); + await filesystem.writeFileAtomic(`${project}/.bin/agent-device.cmd`, "@node ..."); + await filesystem.writeFileAtomic( + `${project}/agent-device/package.json`, + JSON.stringify({ bin: { "agent-device": "bin/agent-device.mjs" }, name: "agent-device" }), + ); + await filesystem.writeFileAtomic(`${project}/agent-device/bin/agent-device.mjs`, ""); + await filesystem.writeFileAtomic(`${project}/agent-device/dist/src/daemon.js`, ""); + + await expect( + findAgentDevice(filesystem, "agent-device", `/Windows;${project}/.bin/`, "win32"), + ).resolves.toEqual({ + entry: `${project}/agent-device/dist/src/daemon.js`, + ok: true, + realPath: `${project}/agent-device/bin/agent-device.mjs`, + }); + }); + + it.each([ + ["a command name ending in .cmd, looked up on PATH", "agent-device.CMD", npm], + ["a configured path to the shim", `${npm}/agent-device.cmd`, undefined], + ])("stands in the package's bin for %s on Windows", async (_case, command, pathVariable) => { + const filesystem = await windowsNpmInstall(); + + await expect(findAgentDevice(filesystem, command, pathVariable, "win32")).resolves.toEqual({ + entry: `${packageRoot}/dist/src/internal/daemon.js`, + ok: true, + realPath: `${packageRoot}/bin/agent-device.mjs`, + }); + }); + + it("does not take a package with no .cmd shim beside it as the command on Windows", async () => { + const filesystem = await windowsNpmInstall({ shim: false }); + + await expect(findAgentDevice(filesystem, "agent-device", npm, "win32")).resolves.toMatchObject({ + ok: false, + reason: "not-found", + }); + }); + + it("accepts a configured path to the bin file on Windows, where no file has an execute bit", async () => { + const filesystem = await windowsNpmInstall(); + const bin = `${packageRoot}/bin/agent-device.mjs`; + + await expect(findAgentDevice(filesystem, bin, undefined, "win32")).resolves.toMatchObject({ + ok: true, + realPath: bin, + }); + await expect(findAgentDevice(filesystem, bin, undefined, "linux")).resolves.toMatchObject({ + ok: false, + reason: "not-found", + }); + }); + + it("still splits PATH on ':' and ignores .cmd shims off Windows", async () => { + const filesystem = await windowsNpmInstall(); + await filesystem.mkdirp("/opt/bin"); + await filesystem.writeFileAtomic("/opt/bin/agent-device", "#!/bin/sh\n"); + filesystem.defineAttributes("/opt/bin/agent-device", { mode: 0o755 }); + + await expect( + findAgentDevice(filesystem, "agent-device", `/usr/bin:${npm}`, "linux"), + ).resolves.toMatchObject({ ok: false, reason: "not-found" }); + await expect( + findAgentDevice(filesystem, "agent-device", "/usr/bin:/opt/bin", "linux"), + ).resolves.toMatchObject({ ok: false, reason: "not-agent-device" }); + }); + + it("takes a command with a backslash as a path on Windows only", async () => { + const filesystem = new MemoryFilesystem(); + const command = "C:\\Users\\me\\agent-device.mjs"; + + await expect(findAgentDevice(filesystem, command, undefined, "win32")).resolves.toMatchObject({ + message: `agent-device not found: ${command} is not an executable file`, + }); + await expect(findAgentDevice(filesystem, command, undefined, "linux")).resolves.toMatchObject({ + message: `agent-device not found: "${command}" is not on PATH`, + }); + }); +}); + +describe.runIf(process.platform === "win32")("findAgentDevice on Windows", () => { + it("finds a local install from a PATH entry that is a project's node_modules .bin, written with backslashes", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock agent-device ")); + const modules = join(directory, "node_modules"); + const packageRoot = join(modules, "agent-device"); + try { + await mkdir(join(modules, ".bin"), { recursive: true }); + await mkdir(join(packageRoot, "bin"), { recursive: true }); + await mkdir(join(packageRoot, "dist", "src"), { recursive: true }); + await writeFile(join(modules, ".bin", "agent-device.cmd"), "@node ..."); + await writeFile( + join(packageRoot, "package.json"), + JSON.stringify({ bin: { "agent-device": "bin/agent-device.mjs" }, name: "agent-device" }), + ); + await writeFile(join(packageRoot, "bin", "agent-device.mjs"), ""); + await writeFile(join(packageRoot, "dist", "src", "daemon.js"), ""); + + await expect( + findAgentDevice(new NodeFilesystem(), "agent-device", join(modules, ".bin"), "win32"), + ).resolves.toMatchObject({ + ok: true, + realPath: join(packageRoot, "bin", "agent-device.mjs"), + }); + } finally { + await rm(directory, { force: true, recursive: true }); + } + }); +}); + +describe("pathVariableOf", () => { + it.each([ + ["PATH", { PATH: "/usr/bin" }, "/usr/bin"], + ["Windows' Path", { Path: "C:\\npm;C:\\bin" }, "C:\\npm;C:\\bin"], + ["none", { HOME: "/home/me" }, undefined], + ])("reads %s", (_name, environment, expected) => { + expect(pathVariableOf(environment)).toBe(expected); + }); +}); diff --git a/src/agent-device/host/install.ts b/src/agent-device/host/install.ts index eba41e677..1aa2b00c7 100644 --- a/src/agent-device/host/install.ts +++ b/src/agent-device/host/install.ts @@ -1,4 +1,4 @@ -import { dirname } from "node:path"; +import { dirname, win32 } from "node:path"; import { type Filesystem } from "../../ports/index.js"; @@ -10,31 +10,114 @@ export type AgentDeviceInstall = readonly message: string; }; -async function isExecutableFile(filesystem: Filesystem, path: string): Promise { +// why: Windows has no execute bit; Node reports a file there as 0o666 (0o444 when read-only), so any file counts. +async function isExecutableFile( + filesystem: Filesystem, + path: string, + windows: boolean, +): Promise { try { const details = await filesystem.stat(path); - return details.kind === "file" && ((details.mode ?? 0) & 0o111) !== 0; + return details.kind === "file" && (windows || ((details.mode ?? 0) & 0o111) !== 0); } catch { return false; } } +const SHIM_SUFFIX = /\.cmd$/i; + +/** + * why: npm on Windows installs a `.cmd` shim, not a symlink. `node` cannot run the shim, + * and its real path is itself, so the package's own `bin` file stands in for it: `--version` runs + * it, and the package root is above it. A configured name or path may already end in `.cmd`. + */ +async function npmShimTarget( + filesystem: Filesystem, + directory: string, + command: string, +): Promise { + const name = command.replace(SHIM_SUFFIX, ""); + const shimDirectory = directory.replace(/[\\/]+$/, ""); + if (!(await isExecutableFile(filesystem, `${shimDirectory}/${name}.cmd`, true))) return undefined; + return packageBin(filesystem, packageRootBeside(shimDirectory, name), name); +} + +// why: a global install puts its shims beside `node_modules`; a local one puts them in `node_modules/.bin`, beside the package. +function packageRootBeside(shimDirectory: string, name: string): string { + return /(^|[\\/])node_modules[\\/]\.bin$/i.test(shimDirectory) + ? `${win32.dirname(shimDirectory)}/${name}` + : `${shimDirectory}/node_modules/${name}`; +} + +async function packageBin( + filesystem: Filesystem, + packageRoot: string, + name: string, +): Promise { + try { + const { bin } = JSON.parse(await filesystem.readFile(`${packageRoot}/package.json`)) as { + bin?: unknown; + }; + const relative = + typeof bin === "string" ? bin : (bin as Record | undefined)?.[name]; + if (typeof relative !== "string") return undefined; + const target = `${packageRoot}/${relative.replace(/^\.\//, "")}`; + return (await isExecutableFile(filesystem, target, true)) ? target : undefined; + } catch { + return undefined; + } +} + +function isPath(command: string, windows: boolean): boolean { + return command.includes("/") || (windows && command.includes("\\")); +} + +async function locatePath( + filesystem: Filesystem, + command: string, + windows: boolean, +): Promise { + if (windows && SHIM_SUFFIX.test(command)) { + return npmShimTarget(filesystem, win32.dirname(command), win32.basename(command)); + } + return (await isExecutableFile(filesystem, command, windows)) ? command : undefined; +} + +async function executableIn( + filesystem: Filesystem, + directory: string, + command: string, +): Promise { + const candidate = `${directory}/${command}`; + return (await isExecutableFile(filesystem, candidate, false)) ? candidate : undefined; +} + async function locate( filesystem: Filesystem, command: string, pathVariable: string | undefined, + platform: NodeJS.Platform, ): Promise { - if (command.includes("/")) { - return (await isExecutableFile(filesystem, command)) ? command : undefined; - } - for (const directory of (pathVariable ?? "").split(":")) { + const windows = platform === "win32"; + if (isPath(command, windows)) return locatePath(filesystem, command, windows); + const lookIn = windows ? npmShimTarget : executableIn; + // why: Windows separates PATH entries with `;`, and its drive letters hold a `:`. + for (const directory of (pathVariable ?? "").split(windows ? ";" : ":")) { if (directory === "") continue; - const candidate = `${directory}/${command}`; - if (await isExecutableFile(filesystem, candidate)) return candidate; + const candidate = await lookIn(filesystem, directory, command); + if (candidate !== undefined) return candidate; } return undefined; } +/** why: on Windows the variable is `Path`, and a copy of `process.env` loses its case-insensitive lookup. */ +export function pathVariableOf(environment: NodeJS.ProcessEnv): string | undefined { + return ( + environment["PATH"] ?? + Object.entries(environment).find(([key]) => key.toUpperCase() === "PATH")?.[1] + ); +} + // why: a pnpm global install puts a shell launcher in PNPM_HOME/bin, not a symlink into the // package; the launcher records the real CLI in a `cmd-shim-target` comment. async function pnpmShimTarget(filesystem: Filesystem, file: string): Promise { @@ -47,12 +130,13 @@ export async function findAgentDevice( filesystem: Filesystem, command: string, pathVariable: string | undefined, + platform: NodeJS.Platform, ): Promise { - const found = await locate(filesystem, command, pathVariable); + const found = await locate(filesystem, command, pathVariable, platform); const notFound = { ok: false, reason: "not-found", - message: command.includes("/") + message: isPath(command, platform === "win32") ? `agent-device not found: ${command} is not an executable file` : `agent-device not found: "${command}" is not on PATH`, } as const; diff --git a/src/agent-device/host/upstream.test.ts b/src/agent-device/host/upstream.test.ts index f52d9b200..b70961a78 100644 --- a/src/agent-device/host/upstream.test.ts +++ b/src/agent-device/host/upstream.test.ts @@ -73,6 +73,7 @@ async function arrange(version: string) { filesystem, healthProbe: health, home, + hostPlatform: "linux", leaseMaxTtlMs, logger: new JsonLinesLogger({ clock, level: "debug", sink: new MemoryLogSink() }), nodePath, diff --git a/src/agent-device/worker.ts b/src/agent-device/worker.ts index d01b26adf..9a951be7f 100644 --- a/src/agent-device/worker.ts +++ b/src/agent-device/worker.ts @@ -127,6 +127,7 @@ export function createWorkerWith( logger: ctx.logger, nodePath: ctx.nodePath, nodeVersion: ctx.nodeVersion, + hostPlatform: ctx.hostPlatform, platforms: ctx.platforms, processRunner: ctx.processRunner, processSupervisor: ctx.processSupervisor, diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 30824a9d2..1e4853885 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -511,6 +511,7 @@ async function composeDaemon( leaseEnvironment, nodePath: process.execPath, nodeVersion: process.versions.node, + hostPlatform: process.platform, platforms: drivers.map((driver) => driver.platform), processRunner, processSupervisor, diff --git a/src/modules/testing.ts b/src/modules/testing.ts index e1e85cb39..17766ced7 100644 --- a/src/modules/testing.ts +++ b/src/modules/testing.ts @@ -186,6 +186,7 @@ export async function fakeWorkerContext(name: string, config: C): Promise { readonly environment: NodeJS.ProcessEnv; readonly nodePath: string; readonly nodeVersion: string; + readonly hostPlatform: NodeJS.Platform; readonly platforms: readonly Platform[]; readonly leaseEnvironment: Readonly>; readonly registry: ModuleRegistryView;