The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Effect from "effect/Effect"; |
| 2 | import * as FileSystem from "effect/FileSystem"; |
| 3 | import * as Option from "effect/Option"; |
| 4 | import * as Path from "effect/Path"; |
| 5 | import * as Schema from "effect/Schema"; |
| 6 | |
| 7 | import type { ServerInstallation } from "@t3tools/contracts"; |
| 8 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 9 | import { resolveCommandPath } from "@t3tools/shared/shell"; |
| 10 | |
| 11 | import packageJson from "../../package.json" with { type: "json" }; |
| 12 | import { |
| 13 | findPosixLauncher, |
| 14 | readPosixLauncherTarget, |
| 15 | resolveLauncherPath, |
| 16 | } from "../cloud/pinnedRuntime.ts"; |
| 17 | |
| 18 | const PINNED_RUNTIME_ENTRY = /^(.*)\/runtime\/versions\/[^/]+\/t3$/; |
| 19 | |
| 20 | export type CliRunner = "npx" | "pnpm dlx" | "bunx"; |
| 21 | |
| 22 | /** Detection is best-effort; callers must fail closed to a plain `t3` command. */ |
| 23 | export function detectCliRunner(entryPath: string): CliRunner | null { |
| 24 | const path = entryPath.replaceAll("\\", "/"); |
| 25 | if (path.includes("/_npx/")) { |
| 26 | return "npx"; |
| 27 | } |
| 28 | if ( |
| 29 | path.includes("/pnpm/dlx/") || |
| 30 | path.includes("/.pnpm/dlx/") || |
| 31 | path.includes("/pnpm-cache/dlx/") |
| 32 | ) { |
| 33 | return "pnpm dlx"; |
| 34 | } |
| 35 | if (path.includes("/.bun/install/cache/") || path.includes("/bunx-")) { |
| 36 | return "bunx"; |
| 37 | } |
| 38 | return null; |
| 39 | } |
| 40 | |
| 41 | const InstallManifest = Schema.Struct({ |
| 42 | name: Schema.String, |
| 43 | version: Schema.String, |
| 44 | bin: Schema.optionalKey(Schema.Struct({ t3: Schema.String })), |
| 45 | }); |
| 46 | const decodeInstallManifest = Schema.decodeUnknownEffect(Schema.fromJsonString(InstallManifest)); |
| 47 | |
| 48 | /** |
| 49 | * `T3CODE_NPM_LAUNCHER_PATH` is inherited by child shells, so accept it only for this package |
| 50 | * version to avoid claiming another `t3` invocation is the npm install. |
| 51 | */ |
| 52 | export const resolveEntryPath = Effect.gen(function* () { |
| 53 | const npmLauncher = (yield* HostProcess.Environment).T3CODE_NPM_LAUNCHER_PATH?.trim(); |
| 54 | if (npmLauncher) { |
| 55 | const fs = yield* FileSystem.FileSystem; |
| 56 | const path = yield* Path.Path; |
| 57 | const manifest = yield* fs |
| 58 | .readFileString(path.join(path.dirname(npmLauncher), "../package.json")) |
| 59 | .pipe(Effect.flatMap(decodeInstallManifest), Effect.option); |
| 60 | if ( |
| 61 | Option.isSome(manifest) && |
| 62 | manifest.value.name === "t3" && |
| 63 | manifest.value.version === packageJson.version |
| 64 | ) { |
| 65 | return npmLauncher; |
| 66 | } |
| 67 | } |
| 68 | if (yield* HostProcess.IsExecutable) return yield* HostProcess.ExecutablePath; |
| 69 | return (yield* HostProcess.Arguments)[1] ?? ""; |
| 70 | }); |
| 71 | |
| 72 | export const resolveServerInstallation = Effect.gen(function* () { |
| 73 | const fs = yield* FileSystem.FileSystem; |
| 74 | const path = yield* Path.Path; |
| 75 | const platform = yield* HostProcess.Platform; |
| 76 | const entry = yield* fs.realPath(yield* resolveEntryPath); |
| 77 | const runtime = PINNED_RUNTIME_ENTRY.exec(entry); |
| 78 | if (runtime) { |
| 79 | const launchedAs = yield* resolveLauncherPath; |
| 80 | if (launchedAs === undefined) return null; |
| 81 | const link = yield* fs.readLink(launchedAs).pipe(Effect.option); |
| 82 | // A launcher script execs the runtime itself, so look for the script that runs it. |
| 83 | const launcher = Option.isSome(link) |
| 84 | ? launchedAs |
| 85 | : yield* findPosixLauncher({ |
| 86 | launchedAs, |
| 87 | versionsDir: path.join(runtime[1] || "/", "runtime/versions"), |
| 88 | }); |
| 89 | // None for a runtime started directly, as SSH launches do, or through a copy. |
| 90 | if (launcher === undefined) return null; |
| 91 | const target = Option.isSome(link) |
| 92 | ? path.resolve(path.dirname(launcher), link.value) |
| 93 | : yield* readPosixLauncherTarget(launcher); |
| 94 | // Keep the home as the launcher spells it; `t3 update` only repoints launchers into that spelling. |
| 95 | const linked = target === undefined ? null : PINNED_RUNTIME_ENTRY.exec(target); |
| 96 | if (!linked || (yield* fs.realPath(linked[1] || "/")) !== (runtime[1] || "/")) return null; |
| 97 | return { |
| 98 | kind: "t3-launcher", |
| 99 | launcher, |
| 100 | baseDir: linked[1] || "/", |
| 101 | } satisfies ServerInstallation; |
| 102 | } |
| 103 | const match = /^(.*)\/lib\/node_modules\/t3\/(?:dist\/bin\.mjs|bin\/t3\.mjs)$/.exec(entry); |
| 104 | if (!match) { |
| 105 | const runner = detectCliRunner(entry); |
| 106 | return runner === null |
| 107 | ? null |
| 108 | : ({ kind: runner === "pnpm dlx" ? "pnpm-dlx" : runner } satisfies ServerInstallation); |
| 109 | } |
| 110 | if (platform === "win32") return null; |
| 111 | const prefix = match[1] || "/"; |
| 112 | if ( |
| 113 | prefix.includes("/node_modules/") || |
| 114 | /\/(?:Cellar|Caskroom)\//i.test(prefix) || |
| 115 | /\/mise\/installs\/(?!node\/)[^/]+\//.test(prefix) |
| 116 | ) |
| 117 | return null; |
| 118 | |
| 119 | const packageRoot = path.join(prefix, "lib/node_modules/t3"); |
| 120 | const manifest = yield* fs |
| 121 | .readFileString(path.join(packageRoot, "package.json")) |
| 122 | .pipe(Effect.flatMap(decodeInstallManifest)); |
| 123 | if (manifest.name !== "t3" || !manifest.bin) return null; |
| 124 | const bin = yield* fs.realPath(path.join(packageRoot, manifest.bin.t3)); |
| 125 | const globalBin = yield* fs.realPath(path.join(prefix, "bin/t3")); |
| 126 | if (globalBin !== bin || bin !== entry) return null; |
| 127 | return { kind: "npm-global", prefix } satisfies ServerInstallation; |
| 128 | }).pipe(Effect.orElseSucceed(() => null)); |
| 129 | |
| 130 | /** The original package spec is unavailable at startup; infer its channel from the version. */ |
| 131 | function suggestedPackageSpec(version: string): string { |
| 132 | const channel = /^[^-+]+-(nightly|preview)\./.exec(version)?.[1]; |
| 133 | return channel === undefined ? "t3" : `t3@${channel}`; |
| 134 | } |
| 135 | |
| 136 | function formatCliCommand(input: { |
| 137 | readonly subcommand: string; |
| 138 | readonly entryPath: string; |
| 139 | readonly version: string; |
| 140 | }): string { |
| 141 | const runner = detectCliRunner(input.entryPath); |
| 142 | if (runner === null) { |
| 143 | return `t3 ${input.subcommand}`; |
| 144 | } |
| 145 | return `${runner} ${suggestedPackageSpec(input.version)} ${input.subcommand}`; |
| 146 | } |
| 147 | |
| 148 | export const resolveCliCommand = (subcommand: string) => |
| 149 | Effect.map(resolveEntryPath, (entryPath) => |
| 150 | formatCliCommand({ subcommand, entryPath, version: packageJson.version }), |
| 151 | ); |
| 152 | |
| 153 | const shellWord = (value: string) => |
| 154 | /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'"'"'`)}'`; |
| 155 | |
| 156 | /** PowerShell also treats typographic quotes as delimiters; escape them and suppress expansion. */ |
| 157 | const powershellWord = (value: string) => |
| 158 | `"${value |
| 159 | .replaceAll("`", "``") |
| 160 | .replaceAll("$", "`$") |
| 161 | .replace(/["\u201C\u201D\u201E]/g, "$&$&")}"`; |
| 162 | |
| 163 | export const hostShellWord = (platform: NodeJS.Platform, value: string) => |
| 164 | platform === "win32" ? powershellWord(value) : shellWord(value); |
| 165 | |
| 166 | /** Script installs have no single launcher; desktop shims and standalone binaries do. */ |
| 167 | const resolveInstallLauncher = Effect.gen(function* () { |
| 168 | const fs = yield* FileSystem.FileSystem; |
| 169 | const shim = (yield* HostProcess.Environment).T3CODE_CLI_PATH?.trim(); |
| 170 | if (shim && (yield* fs.exists(shim).pipe(Effect.orElseSucceed(() => false)))) { |
| 171 | return Option.some(shim); |
| 172 | } |
| 173 | return (yield* HostProcess.IsExecutable) |
| 174 | ? Option.some(yield* HostProcess.ExecutablePath) |
| 175 | : Option.none<string>(); |
| 176 | }); |
| 177 | |
| 178 | /** |
| 179 | * Uses this install's `t3` on PATH, the originating runner, or its absolute launcher path. |
| 180 | * Arguments are quoted for POSIX shells or PowerShell on Windows. |
| 181 | */ |
| 182 | export const resolveHostCliCommand = Effect.fn("invocation.resolveHostCliCommand")(function* ( |
| 183 | subcommand: string, |
| 184 | args: ReadonlyArray<string> = [], |
| 185 | ) { |
| 186 | const platform = yield* HostProcess.Platform; |
| 187 | const withArgs = (prefix: string) => |
| 188 | // An empty subcommand names the root `t3` command. |
| 189 | [prefix.trimEnd(), ...args.map((arg) => hostShellWord(platform, arg))].join(" "); |
| 190 | const command = yield* resolveCliCommand(subcommand); |
| 191 | if (command !== `t3 ${subcommand}`) return { command: withArgs(command), launcher: false }; |
| 192 | const onPath = yield* resolveCommandPath("t3"); |
| 193 | if (onPath !== null) { |
| 194 | const shim = (yield* HostProcess.Environment).T3CODE_CLI_PATH?.trim(); |
| 195 | const fs = yield* FileSystem.FileSystem; |
| 196 | const real = (file: string) => fs.realPath(file).pipe(Effect.orElseSucceed(() => null)); |
| 197 | // Windows `t3.cmd` shims are text files that never realpath to the executable they run. |
| 198 | const own = shim |
| 199 | ? yield* real(shim) |
| 200 | : platform !== "win32" && (yield* HostProcess.IsExecutable) |
| 201 | ? yield* resolveEntryPath.pipe( |
| 202 | Effect.flatMap((entry) => |
| 203 | real(entry).pipe(Effect.map((resolved) => resolved ?? entry)), |
| 204 | ), |
| 205 | ) |
| 206 | : null; |
| 207 | if (own === null || own === (yield* real(onPath))) { |
| 208 | return { command: withArgs(command), launcher: false }; |
| 209 | } |
| 210 | } |
| 211 | const launcher = yield* resolveInstallLauncher; |
| 212 | if (Option.isNone(launcher)) return { command: withArgs(command), launcher: false }; |
| 213 | // PowerShell runs a quoted path only through the call operator. |
| 214 | const quoted = hostShellWord(platform, launcher.value); |
| 215 | const call = platform === "win32" ? `& ${quoted}` : quoted; |
| 216 | return { command: withArgs(`${call} ${subcommand}`), launcher: true }; |
| 217 | }); |
| 218 | |
| 219 | /** A hint's command, run against the caller's `--base-dir` when one was given. */ |
| 220 | export const resolveHostCliHint = ( |
| 221 | subcommand: string, |
| 222 | baseDir: Option.Option<string>, |
| 223 | args: ReadonlyArray<string> = [], |
| 224 | ) => |
| 225 | resolveHostCliCommand(subcommand, [ |
| 226 | ...Option.match(baseDir, { onNone: () => [], onSome: (dir) => ["--base-dir", dir] }), |
| 227 | ...args, |
| 228 | ]).pipe(Effect.map(({ command }) => command)); |
| 229 | |
| 230 | /** |
| 231 | * `sudo` resets PATH on most distributions, which drops a user-installed Node |
| 232 | * (nvm, fnm, a tarball) and with it `npx` or a global `t3`, so the command |
| 233 | * carries PATH through unless Node is on root's PATH too. An absolute launcher |
| 234 | * needs neither. |
| 235 | */ |
| 236 | export const resolveRootCliCommand = Effect.fn("invocation.resolveRootCliCommand")(function* ( |
| 237 | subcommand: string, |
| 238 | args: ReadonlyArray<string> = [], |
| 239 | ) { |
| 240 | const { command, launcher } = yield* resolveHostCliCommand(subcommand, args); |
| 241 | if (launcher) return `sudo ${command}`; |
| 242 | const executablePath = yield* HostProcess.ExecutablePath; |
| 243 | const systemNode = ROOT_PATH_DIRECTORIES.some((directory) => |
| 244 | executablePath.startsWith(`${directory}/`), |
| 245 | ); |
| 246 | return systemNode ? `sudo ${command}` : `sudo env "PATH=$PATH" ${command}`; |
| 247 | }); |
| 248 | |
| 249 | const ROOT_PATH_DIRECTORIES = [ |
| 250 | "/usr/local/sbin", |
| 251 | "/usr/local/bin", |
| 252 | "/usr/sbin", |
| 253 | "/usr/bin", |
| 254 | "/sbin", |
| 255 | "/bin", |
| 256 | ]; |