The best way to control Claude Code, Codex and more from any computer or phone
| 1 | #!/usr/bin/env node |
| 2 | // Share the installer's runtime cache; pre-0.0.41 services re-enter here over IPC. |
| 3 | import { spawn, spawnSync } from "node:child_process"; |
| 4 | import crypto from "node:crypto"; |
| 5 | import fs from "node:fs"; |
| 6 | import os from "node:os"; |
| 7 | import path from "node:path"; |
| 8 | |
| 9 | const { version } = JSON.parse( |
| 10 | fs.readFileSync(path.join(import.meta.dirname, "../package.json"), "utf8"), |
| 11 | ); |
| 12 | |
| 13 | const SUPPORTED = ["darwin-arm64", "linux-arm64", "linux-x64", "win32-arm64", "win32-x64"]; |
| 14 | // Well inside launchd's 20 s ExitTimeOut, which SIGKILLs only the launcher and orphans the runtime. |
| 15 | const TERMINATE_GRACE_MS = 5_000; |
| 16 | |
| 17 | function t3Home() { |
| 18 | const raw = (process.env.T3CODE_HOME || "").trim(); |
| 19 | if (raw === "") return path.join(os.homedir(), ".t3"); |
| 20 | if (raw === "~") return os.homedir(); |
| 21 | if (raw.startsWith("~/") || raw.startsWith("~\\")) return path.join(os.homedir(), raw.slice(2)); |
| 22 | return path.resolve(raw); |
| 23 | } |
| 24 | |
| 25 | const isTransient = (status) => status === 408 || status === 429 || status >= 500; |
| 26 | |
| 27 | async function get(url) { |
| 28 | let response; |
| 29 | for (let attempt = 1; ; attempt++) { |
| 30 | try { |
| 31 | response = await fetch(url); |
| 32 | if (attempt === 4 || !isTransient(response.status)) break; |
| 33 | await response.body?.cancel(); |
| 34 | } catch (error) { |
| 35 | if (attempt === 4) throw error; |
| 36 | } |
| 37 | await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** (attempt - 1))); |
| 38 | } |
| 39 | if (response.status === 404) { |
| 40 | throw new Error( |
| 41 | `${url} does not exist yet. If ${version} was just released, try again in a few minutes.`, |
| 42 | ); |
| 43 | } |
| 44 | if (!response.ok) throw new Error(`GET ${url} returned HTTP ${response.status}`); |
| 45 | return response; |
| 46 | } |
| 47 | |
| 48 | async function download(url, file) { |
| 49 | const response = await get(url); |
| 50 | const total = Number(response.headers.get("content-length")) || 0; |
| 51 | const hash = crypto.createHash("sha256"); |
| 52 | const out = fs.openSync(file, "w"); |
| 53 | const tty = process.stderr.isTTY; |
| 54 | let received = 0; |
| 55 | let shown = -1; |
| 56 | try { |
| 57 | for await (const chunk of response.body) { |
| 58 | hash.update(chunk); |
| 59 | fs.writeSync(out, chunk); |
| 60 | received += chunk.byteLength; |
| 61 | // Redraw once per percent (or per MB without a length), not per chunk. |
| 62 | const step = total ? Math.floor((received * 100) / total) : Math.floor(received / 1048576); |
| 63 | if (tty && step !== shown) { |
| 64 | shown = step; |
| 65 | const percent = total ? ` ${step}%` : ""; |
| 66 | process.stderr.write( |
| 67 | `\r\x1b[2Kt3: downloading T3 Code ${version}${percent} (${(received / 1048576).toFixed(1)} MB)`, |
| 68 | ); |
| 69 | } |
| 70 | } |
| 71 | } finally { |
| 72 | fs.closeSync(out); |
| 73 | if (tty) process.stderr.write("\r\x1b[2K"); |
| 74 | } |
| 75 | return hash.digest("hex"); |
| 76 | } |
| 77 | |
| 78 | async function install(dir, key) { |
| 79 | const archive = `t3-${version}-${key}.${process.platform === "win32" ? "zip" : "tar.gz"}`; |
| 80 | const base = ( |
| 81 | process.env.T3CODE_RELEASE_BASE_URL || "https://github.com/pingdotgg/t3code/releases/download" |
| 82 | ).replace(/\/+$/, ""); |
| 83 | const sums = await (await get(`${base}/v${version}/SHA256SUMS`)).text(); |
| 84 | const expected = /^([0-9a-f]{64})\s+\*?(.+)$/im; |
| 85 | const line = sums |
| 86 | .split(/\r?\n/) |
| 87 | .map((l) => expected.exec(l.trim())) |
| 88 | .find((m) => m && m[2] === archive); |
| 89 | if (!line) throw new Error(`${archive} is not listed in the release's SHA256SUMS`); |
| 90 | |
| 91 | // Stage beside the destination and rename atomically to avoid half-installed versions. |
| 92 | fs.mkdirSync(path.dirname(dir), { recursive: true }); |
| 93 | const staging = fs.mkdtempSync(`${dir}.staging-`); |
| 94 | try { |
| 95 | const file = path.join(staging, archive); |
| 96 | if ((await download(`${base}/v${version}/${archive}`, file)) !== line[1].toLowerCase()) { |
| 97 | throw new Error(`checksum mismatch for ${archive}`); |
| 98 | } |
| 99 | // Windows' own tar.exe reads zip; a Git-for-Windows tar on PATH cannot. |
| 100 | const tar = |
| 101 | process.platform === "win32" ? `${process.env.SystemRoot}\\System32\\tar.exe` : "tar"; |
| 102 | const extract = spawnSync(tar, ["-xf", file, "-C", staging, "--strip-components=1"], { |
| 103 | stdio: "inherit", |
| 104 | }); |
| 105 | if (extract.status !== 0) throw new Error(`could not extract ${archive}`); |
| 106 | fs.rmSync(file); |
| 107 | const validate = spawnSync( |
| 108 | path.join(staging, process.platform === "win32" ? "t3.exe" : "t3"), |
| 109 | ["--version"], |
| 110 | { |
| 111 | stdio: ["ignore", "ignore", "pipe"], |
| 112 | encoding: "utf8", |
| 113 | timeout: 30_000, |
| 114 | killSignal: "SIGKILL", |
| 115 | }, |
| 116 | ); |
| 117 | if (validate.status !== 0) { |
| 118 | throw executableError( |
| 119 | key, |
| 120 | validate.error?.message || |
| 121 | validate.stderr?.trim() || |
| 122 | `--version exited with ${validate.signal || validate.status}`, |
| 123 | ); |
| 124 | } |
| 125 | fs.writeFileSync(path.join(staging, ".install-complete"), `${version}\n`); |
| 126 | publish(staging, dir); |
| 127 | } finally { |
| 128 | fs.rmSync(staging, { recursive: true, force: true }); |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | const isComplete = (dir) => { |
| 133 | try { |
| 134 | return fs.readFileSync(path.join(dir, ".install-complete"), "utf8").trim() === version; |
| 135 | } catch { |
| 136 | return false; |
| 137 | } |
| 138 | }; |
| 139 | |
| 140 | /** Preserve concurrently published complete installs; replace only incomplete folders without the completion marker. */ |
| 141 | function publish(staging, dir) { |
| 142 | try { |
| 143 | fs.renameSync(staging, dir); |
| 144 | return; |
| 145 | } catch (error) { |
| 146 | if (isComplete(dir)) return; |
| 147 | if (!fs.existsSync(dir)) throw error; |
| 148 | } |
| 149 | const lock = `${dir}.lock`; |
| 150 | try { |
| 151 | fs.mkdirSync(lock); |
| 152 | } catch (error) { |
| 153 | if (error.code !== "EEXIST") throw error; |
| 154 | throw new Error( |
| 155 | `another t3 is installing ${version}. If none is running, delete ${lock} and try again.`, |
| 156 | { cause: error }, |
| 157 | ); |
| 158 | } |
| 159 | const stale = `${staging}.stale`; |
| 160 | try { |
| 161 | // A peer may have published between our marker check and taking the lock. |
| 162 | if (isComplete(dir)) return; |
| 163 | // Move it aside rather than deleting in place: once the folder is empty, a |
| 164 | // peer's first rename can land in it. |
| 165 | fs.renameSync(dir, stale); |
| 166 | try { |
| 167 | fs.renameSync(staging, dir); |
| 168 | } catch (error) { |
| 169 | if (!isComplete(dir)) throw error; |
| 170 | } |
| 171 | } finally { |
| 172 | fs.rmSync(lock, { recursive: true, force: true }); |
| 173 | fs.rmSync(stale, { recursive: true, force: true }); |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | async function main() { |
| 178 | const key = `${process.platform}-${process.arch}`; |
| 179 | if (!SUPPORTED.includes(key)) { |
| 180 | throw new Error( |
| 181 | `no T3 Code CLI build is available for ${key} (supported: ${SUPPORTED.join(", ")}).\n` + |
| 182 | "The desktop app is at https://github.com/pingdotgg/t3code/releases", |
| 183 | ); |
| 184 | } |
| 185 | const dir = path.join(t3Home(), "runtime", "versions", version); |
| 186 | if (!isComplete(dir)) await install(dir, key); |
| 187 | |
| 188 | // Service IPC and signals must reach the child; terminal Ctrl-C already does, so do not forward SIGINT twice. |
| 189 | const ipc = process.send !== undefined; |
| 190 | const child = spawn( |
| 191 | path.join(dir, process.platform === "win32" ? "t3.exe" : "t3"), |
| 192 | process.argv.slice(2), |
| 193 | { |
| 194 | stdio: ipc ? ["inherit", "inherit", "inherit", "ipc"] : "inherit", |
| 195 | // The executable lives in the T3 home, so this is how it knows npm launched it. |
| 196 | env: { ...process.env, T3CODE_NPM_LAUNCHER_PATH: import.meta.filename }, |
| 197 | }, |
| 198 | ); |
| 199 | if (ipc) { |
| 200 | process.on("message", (message) => child.connected && child.send(message)); |
| 201 | child.on("message", (message) => process.connected && process.send(message)); |
| 202 | process.on("disconnect", () => child.connected && child.disconnect()); |
| 203 | } |
| 204 | let force; |
| 205 | for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) { |
| 206 | process.on(signal, () => { |
| 207 | if (!ipc && signal === "SIGINT") return; |
| 208 | child.kill(signal); |
| 209 | force ??= setTimeout(() => killTree(child), TERMINATE_GRACE_MS).unref(); |
| 210 | }); |
| 211 | } |
| 212 | child.on("error", (error) => fail(executableError(key, error.message))); |
| 213 | child.on("exit", (code, signal) => |
| 214 | process.exit(code ?? 128 + (os.constants.signals[signal] || 1)), |
| 215 | ); |
| 216 | } |
| 217 | |
| 218 | /** SIGKILL the runtime and its providers, which a runtime stuck on shutdown never stops. */ |
| 219 | function killTree(child) { |
| 220 | const pids = [child.pid]; |
| 221 | if (process.platform !== "win32") { |
| 222 | const table = |
| 223 | spawnSync("ps", ["-A", "-o", "pid=,ppid="], { encoding: "utf8", timeout: 2_000 }).stdout || |
| 224 | ""; |
| 225 | const rows = table |
| 226 | .trim() |
| 227 | .split("\n") |
| 228 | .map((line) => line.trim().split(/\s+/).map(Number)); |
| 229 | for (let i = 0; i < pids.length; i++) { |
| 230 | for (const [pid, ppid] of rows) if (ppid === pids[i]) pids.push(pid); |
| 231 | } |
| 232 | } |
| 233 | for (const pid of pids.slice(1)) { |
| 234 | try { |
| 235 | process.kill(pid, "SIGKILL"); |
| 236 | } catch {} |
| 237 | } |
| 238 | child.kill("SIGKILL"); |
| 239 | } |
| 240 | |
| 241 | function executableError(key, detail) { |
| 242 | return new Error( |
| 243 | `could not run T3 Code ${version} for ${key}: ${detail}` + |
| 244 | (process.platform === "linux" |
| 245 | ? "\nThe Linux release requires glibc; musl-based systems such as Alpine are not supported. Use a glibc-based Linux environment." |
| 246 | : ""), |
| 247 | ); |
| 248 | } |
| 249 | |
| 250 | function fail(error) { |
| 251 | process.stderr.write(`t3: ${error.message}\n`); |
| 252 | process.exit(1); |
| 253 | } |
| 254 | |
| 255 | await main().catch(fail); |