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

main
ts 195 lines 6.86 KB
Raw
1 import { exec } from "node:child_process";
2 import * as crypto from "node:crypto";
3 import * as fs from "node:fs/promises";
4 import * as os from "node:os";
5 import * as nodePath from "node:path";
6 import * as Effect from "effect/Effect";
7 import packageJson from "../../package.json" with { type: "json" };
8 import { rootDir } from "../Auth/Paths.ts";
9
10 const idPath = () => nodePath.join(rootDir(), "id");
11 const disabledPath = () => nodePath.join(rootDir(), "telemetry-disabled");
12
13 /**
14 * OTel resource attributes describing the user, project, runtime, and
15 * environment running the alchemy CLI. Computed once per process and
16 * attached to every span and metric exported by `TelemetryLive`.
17 */
18 export interface TelemetryAttributes {
19 readonly "alchemy.user.id": string;
20 readonly "alchemy.session.id": string;
21 readonly "alchemy.version": string;
22 readonly "alchemy.git.root_commit": string;
23 readonly "alchemy.git.origin_hash": string;
24 readonly "alchemy.git.branch_hash": string;
25 readonly "alchemy.runtime.name": string;
26 readonly "alchemy.runtime.version": string;
27 readonly "alchemy.ci.provider": string;
28 readonly "alchemy.ci": boolean;
29 readonly "host.arch": string;
30 readonly "os.type": string;
31 readonly "os.version": string;
32 readonly "host.cpus": number;
33 readonly "host.memory_mb": number;
34 }
35
36 const tryRead = (path: string): Effect.Effect<string | null> =>
37 Effect.tryPromise(() => fs.readFile(path, "utf-8").then((s) => s.trim())).pipe(
38 Effect.orElseSucceed(() => null),
39 );
40
41 const sha256Hex = (input: string): string =>
42 crypto.createHash("sha256").update(input).digest("hex");
43
44 const hashStringOrEmpty = (input: string | null): string =>
45 input == null || input === "" ? "" : sha256Hex(input);
46
47 const execCapture = (cmd: string): Effect.Effect<string | null> =>
48 Effect.callback<string | null>((resume) => {
49 exec(cmd, { timeout: 1500 }, (err, stdout) => {
50 if (err) {
51 resume(Effect.succeed(null));
52 return;
53 }
54 resume(Effect.succeed(stdout.toString().trim()));
55 });
56 });
57
58 const getOrCreateUserId: Effect.Effect<string> = Effect.gen(function* () {
59 const existing = yield* tryRead(idPath());
60 if (existing) return existing;
61
62 const id = crypto.randomUUID();
63 yield* Effect.tryPromise({
64 try: async () => {
65 await fs.mkdir(rootDir(), { recursive: true });
66 await fs.writeFile(idPath(), id);
67 },
68 catch: () => null as never,
69 }).pipe(Effect.ignore);
70 return id;
71 });
72
73 const getRootCommitHash: Effect.Effect<string | null> = execCapture(
74 process.platform === "win32"
75 ? `git rev-list --max-parents=0 HEAD | ForEach-Object { if (-not (git cat-file -p $_ | Select-String "^parent ")) { $_ } }`
76 : `git rev-list --max-parents=0 HEAD | xargs -r -I{} sh -c 'git cat-file -p {} | grep -q "^parent " || echo {}'`,
77 );
78
79 const getGitOriginUrl: Effect.Effect<string | null> = execCapture(
80 "git config --get remote.origin.url",
81 );
82
83 const getBranchName: Effect.Effect<string | null> = execCapture("git rev-parse --abbrev-ref HEAD");
84
85 const getRuntime = (): { name: string; version: string } => {
86 const g = globalThis as unknown as {
87 Bun?: { version: string };
88 Deno?: { version?: { deno?: string } };
89 };
90 if (typeof g.Bun !== "undefined") {
91 return { name: "bun", version: g.Bun.version };
92 }
93 if (typeof g.Deno !== "undefined") {
94 return { name: "deno", version: g.Deno.version?.deno ?? "" };
95 }
96 if (globalThis.process?.versions?.node) {
97 return { name: "node", version: process.versions.node };
98 }
99 return { name: "", version: "" };
100 };
101
102 const CI_PROVIDERS = [
103 { env: "GITHUB_ACTIONS", provider: "GitHub Actions", isCI: true },
104 { env: "GITLAB_CI", provider: "GitLab CI", isCI: true },
105 { env: "CIRCLECI", provider: "CircleCI", isCI: true },
106 { env: "JENKINS_URL", provider: "Jenkins", isCI: true },
107 { env: "TRAVIS", provider: "Travis CI", isCI: true },
108 { env: "BUILDKITE", provider: "Buildkite", isCI: true },
109 { env: "NOW_BUILDER", provider: "Vercel", isCI: true },
110 { env: "VERCEL", provider: "Vercel", isCI: false },
111 ] as const;
112
113 const getCIEnvironment = (): { provider: string; isCI: boolean } => {
114 for (const p of CI_PROVIDERS) {
115 if (process.env[p.env]) {
116 return { provider: p.provider, isCI: p.isCI };
117 }
118 }
119 return { provider: "", isCI: !!process.env.CI };
120 };
121
122 const TELEMETRY_DISABLED_ENV = (): boolean =>
123 !!process.env.ALCHEMY_TELEMETRY_DISABLED || !!process.env.DO_NOT_TRACK || !!process.env.NO_TRACK;
124
125 /**
126 * `true` if telemetry is disabled via environment variable
127 * (`DO_NOT_TRACK`, `NO_TRACK`, `ALCHEMY_TELEMETRY_DISABLED`) or via a
128 * persisted opt-out file at `~/.alchemy/telemetry-disabled`.
129 */
130 export const isTelemetryDisabled: Effect.Effect<boolean> = Effect.gen(function* () {
131 if (TELEMETRY_DISABLED_ENV()) return true;
132 const persisted = yield* tryRead(disabledPath());
133 return persisted === "true";
134 });
135
136 /**
137 * Persists an opt-out so future invocations skip telemetry without needing
138 * an env var.
139 */
140 export const setTelemetryDisabled: Effect.Effect<void> = Effect.tryPromise(async () => {
141 await fs.mkdir(rootDir(), { recursive: true });
142 await fs.writeFile(disabledPath(), "true");
143 }).pipe(Effect.ignore);
144
145 export const setTelemetryEnabled: Effect.Effect<void> = Effect.tryPromise(() =>
146 fs.rm(disabledPath(), { force: true }),
147 ).pipe(Effect.ignore);
148
149 const collectAttributesUncached: Effect.Effect<TelemetryAttributes> = Effect.gen(function* () {
150 const [userId, rootCommit, originUrl, branch] = yield* Effect.all(
151 [getOrCreateUserId, getRootCommitHash, getGitOriginUrl, getBranchName] as const,
152 { concurrency: "unbounded" },
153 );
154
155 const runtime = getRuntime();
156 const ci = getCIEnvironment();
157
158 return {
159 "alchemy.user.id": userId,
160 "alchemy.session.id": process.env.ALCHEMY_TELEMETRY_SESSION_ID ?? crypto.randomUUID(),
161 "alchemy.version": packageJson.version,
162 "alchemy.git.root_commit": rootCommit ?? "",
163 "alchemy.git.origin_hash": hashStringOrEmpty(originUrl),
164 "alchemy.git.branch_hash": hashStringOrEmpty(branch),
165 "alchemy.runtime.name": runtime.name,
166 "alchemy.runtime.version": runtime.version,
167 "alchemy.ci.provider": ci.provider,
168 "alchemy.ci": ci.isCI,
169 "host.arch": os.arch(),
170 "os.type": os.platform(),
171 "os.version": os.release(),
172 "host.cpus": os.cpus().length,
173 "host.memory_mb": Math.round(os.totalmem() / 1024 / 1024),
174 } satisfies TelemetryAttributes;
175 });
176
177 let cachedAttrs: TelemetryAttributes | undefined;
178
179 /**
180 * Resolves the {@link TelemetryAttributes} for the current process. Cached
181 * so file I/O and `git` invocations only run once per CLI invocation; every
182 * subsequent caller gets the same record (and therefore the same session
183 * id).
184 */
185 export const collectAttributes: Effect.Effect<TelemetryAttributes> = Effect.suspend(() =>
186 cachedAttrs !== undefined
187 ? Effect.succeed(cachedAttrs)
188 : collectAttributesUncached.pipe(
189 Effect.tap((a) =>
190 Effect.sync(() => {
191 cachedAttrs = a;
192 }),
193 ),
194 ),
195 );