The best way to control Claude Code, Codex and more from any computer or phone

main
ts 171 lines 5.36 KB
Raw
1 import { EnvironmentMachineKind } from "@t3tools/contracts";
2 import * as HostProcess from "@t3tools/shared/HostProcess";
3 import * as Config from "effect/Config";
4 import * as Effect from "effect/Effect";
5 import * as FileSystem from "effect/FileSystem";
6 import * as Option from "effect/Option";
7
8 import * as ProcessRunner from "../processRunner.ts";
9
10 const DMI_ROOT = "/sys/class/dmi/id";
11 const KERNEL_RELEASE_PATH = "/proc/sys/kernel/osrelease";
12
13 // SMBIOS 3.x System Enclosure types (table 17).
14 const DMI_CHASSIS_KINDS: Readonly<Record<string, EnvironmentMachineKind>> = {
15 "3": "desktop",
16 "4": "desktop",
17 "5": "desktop",
18 "6": "desktop",
19 "7": "desktop",
20 "8": "laptop",
21 "9": "laptop",
22 "10": "laptop",
23 "13": "desktop",
24 "14": "laptop",
25 "15": "desktop",
26 "16": "desktop",
27 "17": "server",
28 "18": "server",
29 "19": "server",
30 "20": "server",
31 "21": "server",
32 "22": "server",
33 "23": "server",
34 "24": "server",
35 "28": "server",
36 "31": "laptop",
37 "32": "laptop",
38 "35": "desktop",
39 };
40
41 // VMs read as cloud regardless of chassis. Match Hyper-V's product, since Surface shares its vendor.
42 const VIRTUALIZATION_MARKERS = [
43 "qemu",
44 "kvm",
45 "bochs",
46 "vmware",
47 "virtualbox",
48 "innotek",
49 "xen",
50 "parallels",
51 "amazon ec2",
52 "google compute engine",
53 "digitalocean",
54 "hetzner",
55 "linode",
56 "vultr",
57 "scaleway",
58 "openstack",
59 "cloud",
60 "virtual machine",
61 ];
62
63 function normalize(value: string | null | undefined): string | null {
64 const trimmed = value?.trim();
65 return trimmed && trimmed.length > 0 ? trimmed : null;
66 }
67
68 function machineKindFromAppleProductName(name: string): EnvironmentMachineKind | null {
69 const normalized = name.trim().toLowerCase().replaceAll(/\s+/g, "");
70 if (normalized.startsWith("macmini")) return "mac-mini";
71 if (normalized.startsWith("macstudio")) return "mac-studio";
72 if (normalized.startsWith("macbook")) return "laptop";
73 if (normalized.startsWith("imac") || normalized.startsWith("macpro")) return "desktop";
74 return null;
75 }
76
77 function machineKindFromDmi(input: {
78 readonly chassisType: string | null;
79 readonly sysVendor: string | null;
80 readonly productName: string | null;
81 }): EnvironmentMachineKind | null {
82 const productName = input.productName ?? "";
83 const vendorAndProduct = `${input.sysVendor ?? ""} ${productName}`.toLowerCase();
84 if (VIRTUALIZATION_MARKERS.some((marker) => vendorAndProduct.includes(marker))) {
85 return "cloud";
86 }
87 const appleKind = machineKindFromAppleProductName(productName);
88 if (appleKind !== null) {
89 return appleKind;
90 }
91 return input.chassisType === null ? null : (DMI_CHASSIS_KINDS[input.chassisType] ?? null);
92 }
93
94 const readOptionalFile = Effect.fn("readOptionalFile")(function* (path: string) {
95 const fileSystem = yield* FileSystem.FileSystem;
96 return yield* fileSystem.readFileString(path).pipe(
97 Effect.map(normalize),
98 Effect.orElseSucceed(() => null),
99 );
100 });
101
102 const runProbe = Effect.fn("runMachineProbe")(function* (input: {
103 readonly command: string;
104 readonly args: ReadonlyArray<string>;
105 }) {
106 const processRunner = yield* ProcessRunner.ProcessRunner;
107 return yield* processRunner
108 .run({
109 command: input.command,
110 args: input.args,
111 timeout: "5 seconds",
112 timeoutBehavior: "timedOutResult",
113 })
114 .pipe(
115 Effect.map((result) => (result.code === 0 ? normalize(result.stdout) : null)),
116 Effect.orElseSucceed(() => null),
117 );
118 });
119
120 // Apple silicon exposes IOKit's marketing name; Intel needs the hw.model fallback.
121 const detectDarwinMachineKind = Effect.fn("detectDarwinMachineKind")(function* () {
122 const ioreg = yield* runProbe({ command: "ioreg", args: ["-rd1", "-n", "product"] });
123 const productName = ioreg?.match(/"product-name"\s*=\s*<"([^"]+)">/)?.[1] ?? null;
124 const fromProductName =
125 productName === null ? null : machineKindFromAppleProductName(productName);
126 if (fromProductName !== null) {
127 return fromProductName;
128 }
129 const model = yield* runProbe({ command: "sysctl", args: ["-n", "hw.model"] });
130 return model === null ? null : machineKindFromAppleProductName(model);
131 });
132
133 const detectLinuxMachineKind = Effect.fn("detectLinuxMachineKind")(function* () {
134 const [kernelRelease, chassisType, sysVendor, productName] = yield* Effect.all([
135 readOptionalFile(KERNEL_RELEASE_PATH),
136 readOptionalFile(`${DMI_ROOT}/chassis_type`),
137 readOptionalFile(`${DMI_ROOT}/sys_vendor`),
138 readOptionalFile(`${DMI_ROOT}/product_name`),
139 ]);
140 // Check WSL first; WSL 2 presents as a Hyper-V VM in DMI.
141 if (kernelRelease?.toLowerCase().includes("microsoft")) {
142 return "linux";
143 }
144 return machineKindFromDmi({ chassisType, sysVendor, productName });
145 });
146
147 // Overrides detection, e.g. for staged demos on a VM that should read as a laptop.
148 const machineKindOverride = Config.schema(
149 EnvironmentMachineKind,
150 "T3CODE_ENVIRONMENT_MACHINE_KIND",
151 ).pipe(Config.option);
152
153 export const detectServerEnvironmentMachineKind = Effect.fn("detectServerEnvironmentMachineKind")(
154 function* () {
155 const override = yield* machineKindOverride.pipe(
156 Effect.orElseSucceed(() => Option.none<EnvironmentMachineKind>()),
157 );
158 if (Option.isSome(override)) {
159 return override.value;
160 }
161 const platform = yield* HostProcess.Platform;
162 switch (platform) {
163 case "darwin":
164 return yield* detectDarwinMachineKind();
165 case "linux":
166 return yield* detectLinuxMachineKind();
167 default:
168 return null;
169 }
170 },
171 );