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

main
ts 327 lines 11.6 KB
Raw
1 import {
2 EnvironmentId,
3 ORCHESTRATION_PROTOCOL_VERSION,
4 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
5 type ExecutionEnvironmentDescriptor,
6 } from "@t3tools/contracts";
7 import * as HostProcess from "@t3tools/shared/HostProcess";
8 import * as Context from "effect/Context";
9 import * as SecureRandom from "effect/crypto/SecureRandom";
10 import * as Effect from "effect/Effect";
11 import * as FileSystem from "effect/FileSystem";
12 import * as Layer from "effect/Layer";
13 import * as Path from "effect/Path";
14 import * as Schema from "effect/Schema";
15
16 import packageJson from "../../package.json" with { type: "json" };
17 import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
18 import { resolveServerInstallation } from "../cli/invocation.ts";
19 import { readAgentActivityPublishingActive } from "../cloud/config.ts";
20 import { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts";
21 import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts";
22 import * as ServerConfig from "../config.ts";
23 import { databaseMigrationHead } from "../persistence/databaseMigrationHead.ts";
24 import * as ProcessRunner from "../processRunner.ts";
25 import { isSpeechPlatformSupported } from "../speech/platform.ts";
26 import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
27 import { detectServerEnvironmentMachineKind } from "./ServerEnvironmentMachine.ts";
28
29 export class ServerEnvironmentIdPersistenceError extends Schema.TaggedError<ServerEnvironmentIdPersistenceError>()(
30 "ServerEnvironmentIdPersistenceError",
31 {
32 operation: Schema.Literals(["check", "read", "write", "initialize"]),
33 environmentIdPath: Schema.String,
34 cause: Schema.optional(Schema.Defect()),
35 },
36 ) {
37 override get message(): string {
38 if (this.operation === "initialize") {
39 return `Server environment ID file is missing or empty after initialization at '${this.environmentIdPath}'.`;
40 }
41 return `Server environment ID ${this.operation} failed at '${this.environmentIdPath}'.`;
42 }
43 }
44
45 export class ServerEnvironment extends Context.Service<
46 ServerEnvironment,
47 {
48 readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
49 readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;
50 }
51 >()("t3/environment/ServerEnvironment") {}
52
53 export class ServerEnvironmentIdentity extends Context.Service<
54 ServerEnvironmentIdentity,
55 {
56 readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
57 }
58 >()("t3/environment/ServerEnvironment/ServerEnvironmentIdentity") {}
59
60 function platformOs(platform: NodeJS.Platform): ExecutionEnvironmentDescriptor["platform"]["os"] {
61 switch (platform) {
62 case "darwin":
63 return "darwin";
64 case "linux":
65 return "linux";
66 case "win32":
67 return "windows";
68 default:
69 return "unknown";
70 }
71 }
72
73 function platformArch(
74 architecture: NodeJS.Architecture,
75 ): ExecutionEnvironmentDescriptor["platform"]["arch"] {
76 switch (architecture) {
77 case "arm64":
78 return "arm64";
79 case "x64":
80 return "x64";
81 default:
82 return "other";
83 }
84 }
85
86 const makeIdentity = Effect.gen(function* () {
87 const fileSystem = yield* FileSystem.FileSystem;
88 const serverConfig = yield* ServerConfig.ServerConfig;
89 const random = yield* SecureRandom.SecureRandom;
90
91 const readPersistedEnvironmentId = Effect.gen(function* () {
92 const exists = yield* fileSystem.exists(serverConfig.environmentIdPath).pipe(
93 Effect.mapError(
94 (cause) =>
95 new ServerEnvironmentIdPersistenceError({
96 operation: "check",
97 environmentIdPath: serverConfig.environmentIdPath,
98 cause,
99 }),
100 ),
101 );
102 if (!exists) {
103 return null;
104 }
105
106 const raw = yield* fileSystem.readFileString(serverConfig.environmentIdPath).pipe(
107 Effect.map((value) => value.trim()),
108 Effect.mapError(
109 (cause) =>
110 new ServerEnvironmentIdPersistenceError({
111 operation: "read",
112 environmentIdPath: serverConfig.environmentIdPath,
113 cause,
114 }),
115 ),
116 );
117
118 return raw.length > 0 ? raw : null;
119 });
120
121 const persistEnvironmentId = Effect.fn("ServerEnvironmentIdentity.persistEnvironmentId")(
122 function* (value: string, mode: "create" | "recover") {
123 const destinationPath =
124 mode === "recover"
125 ? `${serverConfig.environmentIdPath}.recovery`
126 : serverConfig.environmentIdPath;
127 const tempPath = yield* fileSystem.makeTempFileScoped({
128 directory: serverConfig.stateDir,
129 prefix: ".environment-id-",
130 });
131 yield* fileSystem.writeFileString(tempPath, `${value}\n`);
132 // Publish the completed file without replacing an ID created by another process.
133 yield* fileSystem.link(tempPath, destinationPath).pipe(
134 Effect.catchIf(
135 (cause) => cause.reason._tag === "AlreadyExists",
136 () => Effect.void,
137 ),
138 );
139 if (mode === "recover") {
140 // Keep the recovery ID so delayed initializers also publish the same winner.
141 yield* fileSystem.remove(tempPath);
142 yield* fileSystem.copyFile(destinationPath, tempPath);
143 yield* fileSystem.rename(tempPath, serverConfig.environmentIdPath);
144 }
145 },
146 Effect.scoped,
147 Effect.mapError(
148 (cause) =>
149 new ServerEnvironmentIdPersistenceError({
150 operation: "write",
151 environmentIdPath: serverConfig.environmentIdPath,
152 cause,
153 }),
154 ),
155 );
156
157 const environmentIdRaw = yield* Effect.gen(function* () {
158 const persisted = yield* readPersistedEnvironmentId;
159 if (persisted) {
160 return persisted;
161 }
162
163 const generated = yield* random.uuidV4();
164 yield* persistEnvironmentId(generated, "create");
165 let winner = yield* readPersistedEnvironmentId;
166 if (winner === null) {
167 yield* persistEnvironmentId(generated, "recover");
168 winner = yield* readPersistedEnvironmentId;
169 }
170 if (winner === null) {
171 return yield* new ServerEnvironmentIdPersistenceError({
172 operation: "initialize",
173 environmentIdPath: serverConfig.environmentIdPath,
174 });
175 }
176 return winner;
177 });
178
179 const environmentId = EnvironmentId.make(environmentIdRaw);
180 return ServerEnvironmentIdentity.of({
181 getEnvironmentId: Effect.succeed(environmentId),
182 });
183 });
184
185 /** @public */
186 export const make = Effect.gen(function* () {
187 const path = yield* Path.Path;
188 const serverConfig = yield* ServerConfig.ServerConfig;
189 const secrets = yield* ServerSecretStore.ServerSecretStore;
190 const identity = yield* ServerEnvironmentIdentity;
191 const hostPlatform = yield* HostProcess.Platform;
192 const hostArchitecture = yield* HostProcess.Architecture;
193 const hostLibc = hostPlatform === "linux" ? yield* HostProcess.LinuxLibc : undefined;
194 const environmentId = yield* identity.getEnvironmentId;
195 const cwdBaseName = path.basename(serverConfig.cwd).trim();
196 const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });
197 const machine = yield* detectServerEnvironmentMachineKind();
198 const launcher = yield* resolveServiceLauncherMode();
199 const serverSelfUpdate = resolveServerSelfUpdateCapability({
200 desktopManaged: serverConfig.mode === "desktop",
201 launcherManaged: launcher.managed,
202 });
203 const serverInstallation = serverSelfUpdate === null ? yield* resolveServerInstallation : null;
204 // The desktop reports whether it can install updates; requests travel over its control fd.
205 const desktopAppUpdate =
206 serverSelfUpdate === "desktop-managed" &&
207 serverConfig.desktopAppUpdate === true &&
208 serverConfig.desktopTelemetryControlFd !== undefined;
209
210 const databaseMigration = databaseMigrationHead(serverConfig.dbPath);
211 const descriptor: ExecutionEnvironmentDescriptor = {
212 environmentId,
213 label,
214 platform: {
215 os: platformOs(hostPlatform),
216 arch: platformArch(hostArchitecture),
217 ...(machine === null ? {} : { machine }),
218 },
219 serverVersion: packageJson.version,
220 orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
221 ...(databaseMigration === undefined ? {} : { databaseMigration }),
222 capabilities: {
223 repositoryIdentity: true,
224 connectionProbe: true,
225 attachmentUploads: true,
226 accessTokenRenewal: true,
227 questionAttachments: true,
228 fileAttachments: { maxUploadBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES },
229 pullRequests: true,
230 pullRequestChecks: true,
231 issues: true,
232 linkedThreadRefreshes: true,
233 issueLinkedThreads: true,
234 sideChats: true,
235 vcsBranchStatus: true,
236 inlineMessageContext: true,
237 requiredWorktreeBootstrap: true,
238 threadSettlement: true,
239 threadAutoSettlement: true,
240 storageCleanup: true,
241 storageCleanupRun: true,
242 databaseStorage: true,
243 otlpEndpointCheck: true,
244 secretSourceCheck: true,
245 projectWorktreeCleanup: true,
246 settledWorktreeCleanup: true,
247 worktreesDirectory: true,
248 ...(hostPlatform === "darwin" ? { fastWorktreeCheckout: true } : {}),
249 threadAutoSettlementScope: true,
250 threadRestartContinuation: true,
251 projectSettingsOverrides: true,
252 projectProviderInstanceOverrides: true,
253 threadSnooze: true,
254 threadForceStop: true,
255 environmentThemes: true,
256 usageLimitSources: true,
257 providerWorkspaceSnapshotsOnDemand: true,
258 modelCatalogRefresh: true,
259 usagePriceOverrides: true,
260 usageModelAliases: true,
261 threadPinning: true,
262 threadPinReorder: true,
263 threadActiveReorder: true,
264 threadAutoSettleOptOut: true,
265 threadProjectFromScratch: true,
266 threadTitleRegeneration: true,
267 commandOutputStreaming: true,
268 threadVisitedTracking: true,
269 threadPullRequests: true,
270 threadPullRequestWatch: true,
271 pullRequestStackActions: true,
272 threadPullRequestLinking: true,
273 serverResolvedCommandContext: true,
274 threadStop: true,
275 ...(hostPlatform === "win32" ? {} : { localServerStop: true }),
276 previewTunnelSetting: true,
277 environmentIcon: true,
278 projectCloneTracking: true,
279 projectOrganization: true,
280 ignoredFileListing: true,
281 ignoredFileSearch: true,
282 triage: true,
283 oneTimeSchedules: true,
284 freshContext: true,
285 scheduledTaskThreadModes: true,
286 npmReleaseLookup: true,
287 voiceTranscription: isSpeechPlatformSupported(hostPlatform, hostArchitecture, hostLibc),
288 cloudVoiceTranscription: true,
289 ...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
290 ...(serverInstallation === null ? {} : { serverInstallation }),
291 ...(serverSelfUpdate === "boot-service" || desktopAppUpdate
292 ? { serverSelfUpdateProgress: true }
293 : {}),
294 ...(serverSelfUpdate === "boot-service" ? { serverUpdateStaging: true } : {}),
295 ...(desktopAppUpdate ? { desktopAppUpdate: true, desktopAppChannelSwitch: true } : {}),
296 serverBrowser: true,
297 peerLinks: true,
298 mcpModeLimitHeader: true,
299 linkFence: true,
300 linkThreadStream: true,
301 linkClientPairing: true,
302 mcpApprovalCodes: true,
303 peerLinkPairingCodes: true,
304 mcpHostedApproval: true,
305 shellThreadFamilies: true,
306 shellOlderSettled: true,
307 },
308 };
309
310 return ServerEnvironment.of({
311 getEnvironmentId: Effect.succeed(environmentId),
312 // Publishing opt-in and relay links change at runtime; read the capability per request.
313 getDescriptor: readAgentActivityPublishingActive(secrets).pipe(
314 Effect.map((agentActivityPublishing) => ({
315 ...descriptor,
316 capabilities: { ...descriptor.capabilities, agentActivityPublishing },
317 })),
318 ),
319 });
320 });
321
322 export const layerIdentity = Layer.effect(ServerEnvironmentIdentity, makeIdentity);
323
324 export const layer = Layer.effect(ServerEnvironment, make).pipe(
325 Layer.provideMerge(layerIdentity),
326 Layer.provide(ProcessRunner.layer),
327 );