diff --git a/apps/server/src/cli/invocation.test.ts b/apps/server/src/cli/invocation.test.ts index 8310649aa77cb..928e97dc69246 100644 --- a/apps/server/src/cli/invocation.test.ts +++ b/apps/server/src/cli/invocation.test.ts @@ -8,6 +8,7 @@ import * as Path from "effect/Path"; import packageJson from "../../package.json" with { type: "json" }; import { posixLauncherScript } from "../cloud/pinnedRuntime.ts"; import { + hostShellWord, resolveHostCliCommand, resolveRootCliCommand, resolveServerInstallation, @@ -187,6 +188,40 @@ it.layer(NodeServices.layer)("host CLI commands", (it) => { ); }), ); + + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "names the absolute path of a t3 found through a relative PATH entry", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const bin = yield* fs.makeTempDirectoryScoped(); + yield* fs.writeFileString(path.join(bin, "t3"), "#!/bin/sh\n", { mode: 0o755 }); + const hostCommand = (searchPath: string) => + resolveHostCliCommand("doctor").pipe( + Effect.provideService(HostProcess.ExecutablePath, "/usr/bin/node"), + Effect.provideService(HostProcess.Arguments, [ + "/usr/bin/node", + "/opt/t3/lib/node_modules/t3/dist/bin.mjs", + ]), + Effect.provideService(HostProcess.IsExecutable, false), + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(HostProcess.Environment, { PATH: searchPath }), + ); + + // A relative entry was searched from this process's directory, unlike the user's shell. + expect(yield* hostCommand(path.relative(process.cwd(), bin))).toEqual({ + command: `${hostShellWord("linux", path.join(bin, "t3"))} doctor`, + launcher: false, + }); + // An empty entry makes the shell search its own directory first, wherever that is. + expect(yield* hostCommand(`:${bin}`)).toEqual({ + command: `${hostShellWord("linux", path.join(bin, "t3"))} doctor`, + launcher: false, + }); + expect(yield* hostCommand(bin)).toEqual({ command: "t3 doctor", launcher: false }); + }), + ); }); it.layer(NodeServices.layer)("manual server installation ownership", (it) => { diff --git a/apps/server/src/cli/invocation.ts b/apps/server/src/cli/invocation.ts index 4804d44f0e324..69a3a5815bbd6 100644 --- a/apps/server/src/cli/invocation.ts +++ b/apps/server/src/cli/invocation.ts @@ -205,7 +205,16 @@ export const resolveHostCliCommand = Effect.fn("invocation.resolveHostCliCommand ) : null; if (own === null || own === (yield* real(onPath))) { - return { command: withArgs(command), launcher: false }; + const path = yield* Path.Path; + const searchPath = (yield* HostProcess.Environment).PATH ?? ""; + // With an empty or relative PATH entry, plain `t3` depends on the directory it runs from. + const cwdDependent = + platform !== "win32" && + searchPath.length > 0 && + searchPath.split(":").some((entry) => !path.isAbsolute(entry)); + if (!cwdDependent) return { command: withArgs(command), launcher: false }; + const quoted = hostShellWord(platform, path.resolve(onPath)); + return { command: withArgs(`${quoted} ${subcommand}`), launcher: false }; } } const launcher = yield* resolveInstallLauncher; diff --git a/apps/server/src/cli/triage.test.ts b/apps/server/src/cli/triage.test.ts index 25f7baeb3211e..41f4241fade68 100644 --- a/apps/server/src/cli/triage.test.ts +++ b/apps/server/src/cli/triage.test.ts @@ -190,3 +190,51 @@ it.live("a failed agent launch points at the prompt it could not run", () => ), ), ); + +it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "starts an agent found through a relative PATH entry from the session directory", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const binDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-bin-" }); + // Relative to this process, as an entry like "." is to the server that checked it. + const relativeBinDir = NodePath.relative(process.cwd(), binDir); + // Nested deeper than the entry climbs, so from the session directory it leads nowhere. + const climbs = relativeBinDir.split(NodePath.sep).filter((part) => part === "..").length; + const baseDir = NodePath.join( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-cli-" }), + ...Array.from({ length: climbs }, () => "nested"), + ); + NodeFS.mkdirSync(baseDir, { recursive: true }); + NodeFS.writeFileSync(NodePath.join(binDir, "codex"), FAILING_AGENT_POSIX, { mode: 0o755 }); + yield* Effect.acquireRelease( + Effect.sync(() => { + vi.stubEnv("PATH", relativeBinDir); + vi.stubEnv("CODEX_HOME", NodePath.join(baseDir, "codex-home")); + }), + () => Effect.sync(() => vi.unstubAllEnvs()), + ); + const previousExitCode = process.exitCode; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + process.exitCode = previousExitCode; + }), + ); + + yield* Command.runWith(cli, { version: "0.0.0" })([ + "triage", + "--agent", + "codex", + "--base-dir", + baseDir, + ]); + + // The fake agent ran and exited 1, rather than failing to start. + assert.equal(process.exitCode, 1); + assert.include((yield* TestConsole.logLines).join("\n"), "Codex exited with code 1."); + }).pipe( + Effect.provide( + Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer, TestConsole.layer), + ), + ), +); diff --git a/apps/server/src/cli/triage.ts b/apps/server/src/cli/triage.ts index cb0f94b254589..df73347cd9fe4 100644 --- a/apps/server/src/cli/triage.ts +++ b/apps/server/src/cli/triage.ts @@ -4,7 +4,8 @@ import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import * as NodeReadlinePromises from "node:readline/promises"; -import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { isCommandAvailable, resolveCommandPath, resolveSpawnCommand } from "@t3tools/shared/shell"; import * as Config from "effect/Config"; import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; @@ -220,7 +221,14 @@ export const triageCommand = Command.make("triage", { const model = Option.getOrUndefined(flags.model); const launchPrompt = buildTriageLaunchPrompt(promptFilePath); - const spawnSpec = yield* resolveSpawnCommand(selected.command, [ + // The agent starts in the session directory, so a PATH match relative to this one would + // be searched from there. Windows keeps the bare name for its .cmd shim handling. + const onPath = + (yield* HostProcess.Platform) === "win32" + ? null + : yield* resolveCommandPath(selected.command); + const command = onPath === null ? selected.command : NodePath.resolve(onPath); + const spawnSpec = yield* resolveSpawnCommand(command, [ ...(model === undefined ? [] : ["--model", model]), ...(selected.promptArgs ?? []), launchPrompt, diff --git a/apps/server/src/cloud/pinnedRuntime.test.ts b/apps/server/src/cloud/pinnedRuntime.test.ts index 28a7d720c525f..d5f15cd1b4591 100644 --- a/apps/server/src/cloud/pinnedRuntime.test.ts +++ b/apps/server/src/cloud/pinnedRuntime.test.ts @@ -18,6 +18,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as ProcessRunner from "../processRunner.ts"; import { + findPosixLauncher, isVersionExecutable, ensurePinnedRuntimeInstalled, isUnpublishedRelease, @@ -25,7 +26,9 @@ import { pinnedRuntimePaths, PinnedRuntimeInstallError, type PinnedRuntimeProgress, + posixLauncherScript, prunePinnedRuntimes, + resolveLauncherPath, } from "./pinnedRuntime.ts"; import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts"; @@ -987,3 +990,67 @@ it.layer(NodeServices.layer)("prunePinnedRuntimes", (it) => { }), ); }); + +// NTFS reports no exec bits, and these lookups pass over files without them. +const posixHost = HostProcess.Platform.defaultValue() !== "win32"; + +it.layer(NodeServices.layer)("launcher lookup on PATH", (it) => { + it.effect.skipIf(!posixHost)( + "resolves an empty entry of a nonempty PATH against the working directory", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-launcher-path-" }); + const launcher = path.join(root, "t3"); + yield* fs.writeFileString(launcher, "", { mode: 0o755 }); + const missing = path.join(root, "missing"); + const lookup = (platform: NodeJS.Platform, searchPath: string) => + resolveLauncherPath.pipe( + Effect.provideService(HostProcess.InvokedAs, "t3"), + Effect.provideService(HostProcess.Platform, platform), + Effect.provideService(HostProcess.Environment, { PATH: searchPath }), + Effect.provideService(HostProcess.WorkingDirectory, root), + ); + + assert.equal(yield* lookup("linux", `:${missing}`), launcher); + assert.equal(yield* lookup("linux", `${missing}:`), launcher); + assert.equal(yield* lookup("linux", `${missing}::${missing}`), launcher); + // An empty PATH searches nothing, and Windows has no such rule. + assert.isUndefined(yield* lookup("linux", "")); + assert.isUndefined(yield* lookup("win32", `;${missing}`)); + }), + ); + + it.effect.skipIf(!posixHost)("finds a launcher script through an empty PATH entry", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-launcher-path-" }); + const versionsDir = path.join(root, ".t3", "runtime", "versions"); + const executable = path.join(versionsDir, "1.0.0", "t3"); + yield* fs.makeDirectory(path.dirname(executable), { recursive: true }); + yield* fs.writeFileString(executable, "", { mode: 0o755 }); + const bin = path.join(root, "bin"); + yield* fs.makeDirectory(bin); + yield* fs.writeFileString(path.join(bin, "t3"), posixLauncherScript(executable), { + mode: 0o755, + }); + const script = yield* fs.realPath(path.join(bin, "t3")); + const missing = path.join(root, "missing"); + const lookup = (searchPath: string) => + findPosixLauncher({ launchedAs: executable, versionsDir }).pipe( + Effect.provideService(HostProcess.Environment, { + PATH: searchPath, + T3CODE_INSTALL_BIN_DIR: missing, + }), + Effect.provideService(HostProcess.WorkingDirectory, bin), + ); + + assert.equal(yield* lookup(`:${missing}`), script); + assert.equal(yield* lookup(`${missing}:`), script); + // An empty PATH searches nothing, not even the working directory. + assert.isUndefined(yield* lookup("")); + }), + ); +}); diff --git a/apps/server/src/cloud/pinnedRuntime.ts b/apps/server/src/cloud/pinnedRuntime.ts index 13c8f251c93b6..e544852ef3dcc 100644 --- a/apps/server/src/cloud/pinnedRuntime.ts +++ b/apps/server/src/cloud/pinnedRuntime.ts @@ -537,9 +537,11 @@ export const resolveLauncherPath = Effect.gen(function* () { return path.resolve(cwd, invokedAs); } const delimiter = platform === "win32" ? ";" : ":"; - for (const directory of (environment["PATH"] ?? "").split(delimiter)) { - if (directory.length === 0) continue; - const candidate = path.resolve(cwd, directory, invokedAs); + const searchPath = environment["PATH"] ?? ""; + for (const directory of searchPath.split(delimiter)) { + // POSIX shells search the working directory for an empty entry of a nonempty PATH. + if (directory.length === 0 && (platform === "win32" || searchPath.length === 0)) continue; + const candidate = path.resolve(cwd, directory || ".", invokedAs); const info = yield* fs.stat(candidate).pipe(Effect.option); // Like the shell, pass over directories and non-executable files named the same. if ( @@ -645,12 +647,13 @@ export const findPosixLauncher = Effect.fn("cloud.pinned_runtime.find_posix_laun .readFileString(path.join(path.dirname(input.versionsDir), "launchers")) .pipe(Effect.orElseSucceed(() => "")); const cwd = yield* HostProcess.WorkingDirectory; + const searchPath = environment["PATH"] ?? ""; const candidates = [ - // PATH first, resolved like the shell does: it decides which t3 the user runs. - ...(environment["PATH"] ?? "") - .split(":") - .filter((directory) => directory.length > 0) - .map((directory) => path.resolve(cwd, directory, "t3")), + // PATH first, resolved like the shell does: it decides which t3 the user runs. An empty + // entry of a nonempty PATH is the working directory; an empty PATH searches nothing. + ...(searchPath.length === 0 ? [] : searchPath.split(":")).map((directory) => + path.resolve(cwd, directory || ".", "t3"), + ), path.join( environment["T3CODE_INSTALL_BIN_DIR"] || path.join(yield* HostProcess.HomeDirectory, ".local", "bin"), diff --git a/apps/server/src/cloud/serviceLauncherClient.test.ts b/apps/server/src/cloud/serviceLauncherClient.test.ts index 338ff32a3c16e..85661360020f6 100644 --- a/apps/server/src/cloud/serviceLauncherClient.test.ts +++ b/apps/server/src/cloud/serviceLauncherClient.test.ts @@ -325,4 +325,71 @@ it.layer(NodeServices.layer)("self-update launchers", (it) => { assert.equal(yield* fs.readLink(onPath), foreign); }).pipe(Effect.provideService(HostProcess.Platform, "linux")), ); + + it.effect.each([ + { name: "leading", searchPath: (missing: string) => `:${missing}`, moved: true }, + { name: "trailing", searchPath: (missing: string) => `${missing}:`, moved: true }, + { name: "whole", searchPath: () => "", moved: false }, + ])("treats a $name empty PATH entry like the shell does", ({ searchPath, moved }) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" }); + const baseDir = path.join(root, ".t3"); + const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3"); + const cwd = path.join(root, "work"); + const inCwd = path.join(cwd, "t3"); + for (const file of [exe("1.0.0"), exe("2.0.0")]) { + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, "", { mode: 0o755 }); + } + yield* fs.makeDirectory(cwd); + yield* fs.symlink(exe("1.0.0"), inCwd); + + yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe( + Effect.provideService(HostProcess.Environment, { + HOME: root, + PATH: searchPath(path.join(root, "missing")), + }), + Effect.provideService(HostProcess.WorkingDirectory, cwd), + ); + + // A nonempty PATH searches the working directory there; an empty PATH searches nothing. + if (moved) { + assert.equal(yield* fs.readFileString(inCwd), posixLauncherScript(exe("2.0.0"))); + } else { + assert.equal(yield* fs.readLink(inCwd), exe("1.0.0")); + } + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), + ); + + it.effect("passes over a working-directory t3 the shell cannot run", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" }); + const baseDir = path.join(root, ".t3"); + const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3"); + const cwd = path.join(root, "work"); + const onPath = path.join(root, "bin/t3"); + for (const file of [exe("1.0.0"), exe("2.0.0")]) { + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, "", { mode: 0o755 }); + } + // A directory named t3 in the working directory, which the shell skips. + yield* fs.makeDirectory(path.join(cwd, "t3"), { recursive: true }); + yield* fs.makeDirectory(path.dirname(onPath), { recursive: true }); + yield* fs.symlink(exe("1.0.0"), onPath); + + yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe( + Effect.provideService(HostProcess.Environment, { + HOME: root, + PATH: `:${path.dirname(onPath)}`, + }), + Effect.provideService(HostProcess.WorkingDirectory, cwd), + ); + + assert.equal(yield* fs.readFileString(onPath), posixLauncherScript(exe("2.0.0"))); + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), + ); }); diff --git a/apps/server/src/cloud/serviceLauncherClient.ts b/apps/server/src/cloud/serviceLauncherClient.ts index e8f8941f3f9e8..3e7f4abfc2d57 100644 --- a/apps/server/src/cloud/serviceLauncherClient.ts +++ b/apps/server/src/cloud/serviceLauncherClient.ts @@ -163,9 +163,21 @@ export const repointLaunchers = Effect.fn("cloud.service_launcher_client.repoint (environment["HOME"] ? path.join(environment["HOME"], ".local", "bin") : undefined); const candidates = new Set(); if (installBinDir !== undefined) candidates.add(path.join(installBinDir, "t3")); - for (const directory of (environment["PATH"] ?? "").split(":")) { - if (directory.length === 0) continue; - const candidate = path.join(directory, "t3"); + const searchPath = environment["PATH"] ?? ""; + const cwd = yield* HostProcess.WorkingDirectory; + for (const directory of searchPath.split(":")) { + // Like the shell, an empty entry of a nonempty PATH is the working directory. + if (directory.length === 0 && searchPath.length === 0) continue; + const candidate = path.join(directory || cwd, "t3"); + if (directory.length === 0) { + // The shell passes over a working-directory entry it cannot run and keeps searching. + const info = yield* fs.stat(candidate).pipe(Effect.option); + if (Option.isNone(info) || info.value.type !== "File" || (info.value.mode & 0o111) === 0) { + continue; + } + candidates.add(candidate); + break; + } if ( yield* fs.exists(candidate).pipe( Effect.catch((cause) => diff --git a/packages/shared/src/relayClient.test.ts b/packages/shared/src/relayClient.test.ts index 594d5ad215b1a..f317cc22b3565 100644 --- a/packages/shared/src/relayClient.test.ts +++ b/packages/shared/src/relayClient.test.ts @@ -717,6 +717,45 @@ describe("RelayClient", () => { ); }); + it.effect.skipIf(windowsHost)( + "finds a PATH binary through an empty entry by its absolute path", + () => + run((baseDir) => + Effect.gen(function* () { + const cwd = `${baseDir}/work`; + const inCwd = `${cwd}/cloudflared`; + yield* writeExecutable(inCwd); + const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir }); + const resolveWith = (searchPath: string) => { + const env = { PATH: searchPath }; + return manager.resolve.pipe( + Effect.provideService( + ConfigProvider.ConfigProvider, + ConfigProvider.fromEnv({ env }), + ), + Effect.provideService(HostProcess.Environment, env), + Effect.provideService(HostProcess.WorkingDirectory, cwd), + ); + }; + const found = { + status: "available", + executablePath: inCwd, + source: "path", + version: RelayClient.CLOUDFLARED_VERSION, + }; + + expect(yield* resolveWith(`:${baseDir}/missing`)).toEqual(found); + expect(yield* resolveWith(`${baseDir}/missing:`)).toEqual(found); + const missing = { status: "missing", version: RelayClient.CLOUDFLARED_VERSION }; + // An empty PATH searches nothing, not even the working directory. + expect(yield* resolveWith("")).toEqual(missing); + // A whitespace entry is not an empty one. + expect(yield* resolveWith(` :${baseDir}/missing`)).toEqual(missing); + expect(yield* resolveWith(`${baseDir}/missing: `)).toEqual(missing); + }), + ), + ); + it.effect.skipIf(windowsHost)("reports an outdated override as missing", () => { const versions: Record = {}; return run( diff --git a/packages/shared/src/relayClient.ts b/packages/shared/src/relayClient.ts index 19e42955ea554..81838ea4f65a0 100644 --- a/packages/shared/src/relayClient.ts +++ b/packages/shared/src/relayClient.ts @@ -374,13 +374,21 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function const resolvePathExecutable = Effect.gen(function* () { // Read hydrated PATH directly; ConfigProvider may have cached it before fixPath. - const pathValue = (yield* HostProcess.Environment).PATH?.trim(); + const rawPathValue = (yield* HostProcess.Environment).PATH; + // POSIX keeps the raw value, so trimming never turns " :/bin" into an empty entry. + const pathValue = platform === "win32" ? rawPathValue?.trim() : rawPathValue; if (!pathValue) return null; const delimiter = platform === "win32" ? ";" : ":"; + const cwd = yield* HostProcess.WorkingDirectory; for (const directory of pathValue.split(delimiter)) { + // POSIX shells search the working directory for an empty entry. Resolve it now: the + // connector may be launched from elsewhere. + const workingDirectoryEntry = directory === "" && platform !== "win32"; const trimmed = directory.trim().replace(/^"|"$/gu, ""); - if (trimmed.length === 0) continue; - const candidate = path.join(trimmed, executableFileName(platform)); + if (trimmed.length === 0 && !workingDirectoryEntry) continue; + const candidate = workingDirectoryEntry + ? path.resolve(cwd, executableFileName(platform)) + : path.join(trimmed, executableFileName(platform)); if (!(yield* isExecutableFile(candidate))) continue; const available = yield* compatibleCandidate(candidate, "path"); if (available) return available;