@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 137 lines 5.46 KB
Raw
1 import { AlchemyContext } from "alchemy/AlchemyContext";
2 import * as Clock from "effect/Clock";
3 import * as Data from "effect/Data";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import * as Fiber from "effect/Fiber";
7 import * as FileSystem from "effect/FileSystem";
8 import * as HttpClient from "effect/http/HttpClient";
9 import * as Path from "effect/Path";
10 import * as Result from "effect/Result";
11 import * as SemVer from "effect/SemVer";
12 import packageJson from "../../package.json" with { type: "json" };
13
14 export class CheckVersionUnexpectedResponse extends Data.TaggedError(
15 "CheckVersionUnexpectedResponse",
16 )<{
17 readonly message: string;
18 readonly cause?: unknown;
19 }> {}
20
21 const NPM_DIST_TAGS_URL = "https://registry.npmjs.org/-/package/alchemy/dist-tags";
22
23 const CACHE_FILE = "version-check.json";
24 const CACHE_TTL_MILLIS = Duration.toMillis(Duration.days(1));
25 // npm's dist-tags endpoint is CDN-backed and typically answers in ~100ms;
26 // the sync budget only needs to absorb a slow handshake, not a dead network.
27 const SYNC_WAIT = Duration.seconds(3);
28
29 interface VersionCheckCache {
30 checkedAt: number;
31 /** Absent when the last check attempt failed (offline, timeout, …). */
32 distTags?: Record<string, string>;
33 }
34
35 /**
36 * Semver precedence: negative when a < b, positive when a > b. Versions that
37 * don't parse compare equal, so they never trigger an upgrade notice.
38 */
39 const compareVersions = (a: string, b: string): number => {
40 const pa = Result.getOrUndefined(SemVer.parse(a));
41 const pb = Result.getOrUndefined(SemVer.parse(b));
42 return pa === undefined || pb === undefined ? 0 : SemVer.Order(pa, pb);
43 };
44
45 const readCache = Effect.fn(
46 function* (cachePath: string) {
47 const fs = yield* FileSystem.FileSystem;
48 const raw = yield* fs.readFileString(cachePath);
49 const parsed = yield* Effect.try(() => JSON.parse(raw) as VersionCheckCache | null | undefined);
50 return typeof parsed?.checkedAt === "number" ? parsed : undefined;
51 },
52 Effect.orElseSucceed(() => undefined),
53 );
54
55 const writeCache = Effect.fn(
56 function* (cachePath: string, distTags?: Record<string, string>) {
57 const fs = yield* FileSystem.FileSystem;
58 const checkedAt = yield* Clock.currentTimeMillis;
59 const cache: VersionCheckCache = { checkedAt, distTags };
60 yield* fs.writeFileString(cachePath, JSON.stringify(cache));
61 },
62 (effect) => Effect.ignore(effect),
63 );
64
65 const fetchDistTags = Effect.gen(function* () {
66 const http = yield* HttpClient.HttpClient;
67 const response = yield* http.get(NPM_DIST_TAGS_URL);
68 const distTags = (yield* response.json) as Record<string, string> | null;
69 if (typeof distTags !== "object" || distTags === null) {
70 return yield* new CheckVersionUnexpectedResponse({ message: "malformed dist-tags response" });
71 }
72 return distTags;
73 });
74
75 /**
76 * Refresh the dist-tags cache with a single request. The fetch is forked so
77 * it outlives the sync wait: we give it {@link SYNC_WAIT} to land inline,
78 * and if it's still in flight the same request keeps going in the
79 * background, writing the cache when it completes. The background path
80 * never logs, so it can't interleave with prompts.
81 */
82 const refreshDistTags = Effect.fn(function* (cachePath: string) {
83 const fetch = yield* fetchDistTags.pipe(
84 // The fiber owns all cache writes, whenever it completes — even after
85 // the sync wait below has given up on it. A failed attempt is cached
86 // too (a bare checkedAt), so a dead network costs at most one blocking
87 // wait per TTL window, not one per run.
88 Effect.tap((distTags) => writeCache(cachePath, distTags)),
89 Effect.tapError(() => writeCache(cachePath)),
90 Effect.forkScoped,
91 );
92 return yield* Fiber.join(fetch).pipe(
93 Effect.timeout(SYNC_WAIT),
94 Effect.orElseSucceed(() => undefined),
95 );
96 });
97
98 /**
99 * Warn if a newer `alchemy` version is published on the `latest` dist-tag. Runs to completion before any interactive prompts so
100 * the warning never interleaves with prompt rendering, and is bounded so it
101 * can never stall the CLI: dist-tags are cached in
102 * `.alchemy/version-check.json` for a day (failed attempts included), so at
103 * most one run per day waits on the network, and only up to
104 * {@link SYNC_WAIT}. Best-effort: every failure is swallowed silently.
105 */
106 export const checkLatestVersion = Effect.gen(function* () {
107 const path = yield* Path.Path;
108 const { dotAlchemy } = yield* AlchemyContext;
109 const cachePath = path.join(dotAlchemy, CACHE_FILE);
110 const now = yield* Clock.currentTimeMillis;
111
112 const cached = yield* readCache(cachePath);
113 const distTags =
114 cached !== undefined && now - cached.checkedAt <= CACHE_TTL_MILLIS
115 ? cached.distTags
116 : yield* refreshDistTags(cachePath);
117 if (distTags === undefined) return;
118
119 const current = packageJson.version;
120 const { latest } = distTags;
121 // Strictly newer only: `latest` at (or behind) the installed version must
122 // not prompt a "downgrade".
123 if (latest === undefined || compareVersions(latest, current) <= 0) return;
124
125 const installCmd =
126 typeof process !== "undefined" && process.versions.bun !== undefined
127 ? `bun add alchemy@${latest}`
128 : `pnpm add alchemy@${latest}`;
129 // A warning record: above the default console floor, and a JSON record
130 // under --log-format json (commands run this check, after the flags parse).
131 yield* Effect.logWarning(
132 `alchemy ${latest} is available (you're on ${current}). Run \`${installCmd}\` to upgrade.`,
133 );
134 }).pipe(Effect.ignore);
135
136 // Exported for tests.
137 export const _internal = { compareVersions };