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

main
ts 120 lines 4.94 KB
Raw
1 import { ProviderDriverKind } from "@t3tools/contracts";
2 import {
3 makeCachedProviderMaintenanceResolution,
4 makePackageManagedProviderMaintenanceResolver,
5 normalizeCommandPath,
6 resolveProviderMaintenanceCapabilitiesEffect,
7 type ProviderMaintenanceCapabilities,
8 type ProviderMaintenanceResolverServices,
9 } from "@t3tools/provider-core/server/maintenanceResolver";
10 import * as HostProcess from "@t3tools/shared/HostProcess";
11 import { fromLenientJson } from "@t3tools/shared/schemaJson";
12 import * as Effect from "effect/Effect";
13 import * as FileSystem from "effect/FileSystem";
14 import * as Path from "effect/Path";
15 import * as Option from "effect/Option";
16 import * as Schema from "effect/Schema";
17 import * as HttpClient from "effect/http/HttpClient";
18 import * as HttpClientResponse from "effect/http/HttpClientResponse";
19 import { resolveClaudeHomePath } from "./ClaudeHome.ts";
20
21 const NATIVE_RELEASES = "https://downloads.claude.ai/claude-code-releases";
22 const UpdateChannelSettings = fromLenientJson(
23 Schema.Struct({ autoUpdatesChannel: Schema.optional(Schema.Literals(["latest", "stable"])) }),
24 );
25 const NativeVersion = Schema.String.check(Schema.isPattern(/^\d+\.\d+\.\d+$/));
26
27 const update = makePackageManagedProviderMaintenanceResolver({
28 provider: ProviderDriverKind.make("claudeAgent"),
29 npmPackageName: "@anthropic-ai/claude-code",
30 mise: { tool: "claude" },
31 nativeUpdate: {
32 args: ["update"],
33 // On Unix the native launcher links into ${XDG_DATA_HOME:-~/.local/share}/claude/versions; a
34 // plain file at ~/.local/bin/claude is a wrapper whose owner `claude update` cannot see.
35 isCommandPath: (commandPath) => {
36 const normalized = normalizeCommandPath(commandPath);
37 return (
38 normalized.endsWith("/.local/bin/claude.exe") ||
39 normalized.includes("/.local/share/claude/") ||
40 normalized.includes("/claude/versions/")
41 );
42 },
43 requiresCommandPath: true,
44 },
45 });
46
47 const readUpdateChannel = Effect.fn("ClaudeMaintenance.readUpdateChannel")(function* () {
48 const fs = yield* FileSystem.FileSystem;
49 const path = yield* Path.Path;
50 const environment = yield* HostProcess.Environment;
51 const platform = yield* HostProcess.Platform;
52 const managedDirectory =
53 platform === "darwin"
54 ? "/Library/Application Support/ClaudeCode"
55 : platform === "win32"
56 ? path.join(environment.PROGRAMFILES || "C:\\Program Files", "ClaudeCode")
57 : "/etc/claude-code";
58 const dropInDirectory = path.join(managedDirectory, "managed-settings.d");
59 const dropIns = yield* fs.readDirectory(dropInDirectory).pipe(Effect.orElseSucceed(() => []));
60 // The updater inherits the server's config directory, not the instance's homePath.
61 const configDirectory = yield* resolveClaudeHomePath({ homePath: "" }, environment);
62 const settingsPaths = [
63 path.join(configDirectory, "settings.json"),
64 path.join(managedDirectory, "managed-settings.json"),
65 ...dropIns
66 .filter((name) => name.endsWith(".json") && !name.startsWith("."))
67 .toSorted()
68 .map((name) => path.join(dropInDirectory, name)),
69 ];
70 const channels = yield* Effect.forEach(settingsPaths, (settingsPath) =>
71 fs.readFileString(settingsPath).pipe(
72 Effect.flatMap(Schema.decodeUnknownEffect(UpdateChannelSettings)),
73 Effect.map((settings) => settings.autoUpdatesChannel),
74 Effect.orElseSucceed(() => undefined),
75 ),
76 );
77 return channels.findLast((channel) => channel !== undefined) ?? "latest";
78 });
79
80 const resolveClaudeMaintenance = Effect.fn("ClaudeMaintenance.resolve")(function* (
81 capabilities: ProviderMaintenanceCapabilities,
82 ) {
83 if (capabilities.update?.lockKey !== "claudeAgent-native") return capabilities;
84 const channel = yield* readUpdateChannel();
85 const client = yield* HttpClient.HttpClient;
86 const url = `${NATIVE_RELEASES}/${channel}`;
87 return {
88 ...capabilities,
89 latestVersion: null,
90 latestVersionCacheKey: url,
91 lookupLatestVersion: client.get(url).pipe(
92 Effect.flatMap(HttpClientResponse.filterStatusOk),
93 Effect.flatMap((response) => response.text),
94 Effect.map((text) => text.trim()),
95 Effect.flatMap(Schema.decodeUnknownEffect(NativeVersion)),
96 Effect.timeoutOption("4 seconds"),
97 Effect.map(Option.getOrNull),
98 Effect.orElseSucceed(() => null),
99 ),
100 };
101 });
102
103 export const makeClaudeMaintenanceResolution = Effect.fn("ClaudeMaintenance.make")(function* (
104 options: Parameters<typeof resolveProviderMaintenanceCapabilitiesEffect>[1],
105 ) {
106 const services = yield* Effect.context<
107 ProviderMaintenanceResolverServices | HttpClient.HttpClient
108 >();
109 const resolveInstallation = yield* makeCachedProviderMaintenanceResolution(
110 resolveProviderMaintenanceCapabilitiesEffect(update, options).pipe(
111 Effect.provideContext(services),
112 ),
113 );
114 const resolve: typeof resolveInstallation = (refreshOptions) =>
115 resolveInstallation(refreshOptions).pipe(
116 Effect.flatMap(resolveClaudeMaintenance),
117 Effect.provideContext(services),
118 );
119 return resolve;
120 });