Open History to see the last commit
1import {
2 EnvironmentId,
3 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
4 type ExecutionEnvironmentDescriptor,
5} from "@t3tools/contracts";
6import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
7import * as Context from "effect/Context";
8import * as Crypto from "effect/Crypto";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Path from "effect/Path";
13import * as Schema from "effect/Schema";
14
15import packageJson from "../../package.json" with { type: "json" };
16import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
17import { readAgentActivityPublishingActive } from "../cloud/config.ts";
18import { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts";
19import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts";
20import * as ServerConfig from "../config.ts";
21import * as ProcessRunner from "../processRunner.ts";
22import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
23
24export class ServerEnvironmentIdPersistenceError extends Schema.TaggedErrorClass<ServerEnvironmentIdPersistenceError>()(
25 "ServerEnvironmentIdPersistenceError",
26 {
27 operation: Schema.Literals(["check", "read", "write", "initialize"]),
28 environmentIdPath: Schema.String,
29 cause: Schema.optional(Schema.Defect()),
30 },
31) {
32 override get message(): string {
33 if (this.operation === "initialize") {
34 return `Server environment ID file is missing or empty after initialization at '${this.environmentIdPath}'.`;
35 }
36 return `Server environment ID ${this.operation} failed at '${this.environmentIdPath}'.`;
37 }
38}
39
40export class ServerEnvironment extends Context.Service<
41 ServerEnvironment,
42 {
43 readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
44 readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;
45 }
46>()("t3/environment/ServerEnvironment") {}
47
48export class ServerEnvironmentIdentity extends Context.Service<
49 ServerEnvironmentIdentity,
50 {
51 readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
52 }
53>()("t3/environment/ServerEnvironment/ServerEnvironmentIdentity") {}
54
55function platformOs(platform: NodeJS.Platform): ExecutionEnvironmentDescriptor["platform"]["os"] {
56 switch (platform) {
57 case "darwin":
58 return "darwin";
59 case "linux":
60 return "linux";
61 case "win32":
62 return "windows";
63 default:
64 return "unknown";
65 }
66}
67
68function platformArch(
69 architecture: NodeJS.Architecture,
70): ExecutionEnvironmentDescriptor["platform"]["arch"] {
71 switch (architecture) {
72 case "arm64":
73 return "arm64";
74 case "x64":
75 return "x64";
76 default:
77 return "other";
78 }
79}
80
81const makeIdentity = Effect.gen(function* () {
82 const fileSystem = yield* FileSystem.FileSystem;
83 const serverConfig = yield* ServerConfig.ServerConfig;
84 const crypto = yield* Crypto.Crypto;
85
86 const readPersistedEnvironmentId = Effect.gen(function* () {
87 const exists = yield* fileSystem.exists(serverConfig.environmentIdPath).pipe(
88 Effect.mapError(
89 (cause) =>
90 new ServerEnvironmentIdPersistenceError({
91 operation: "check",
92 environmentIdPath: serverConfig.environmentIdPath,
93 cause,
94 }),
95 ),
96 );
97 if (!exists) {
98 return null;
99 }
100
101 const raw = yield* fileSystem.readFileString(serverConfig.environmentIdPath).pipe(
102 Effect.map((value) => value.trim()),
103 Effect.mapError(
104 (cause) =>
105 new ServerEnvironmentIdPersistenceError({
106 operation: "read",
107 environmentIdPath: serverConfig.environmentIdPath,
108 cause,
109 }),
110 ),
111 );
112
113 return raw.length > 0 ? raw : null;
114 });
115
116 const persistEnvironmentId = Effect.fn("ServerEnvironmentIdentity.persistEnvironmentId")(
117 function* (value: string, mode: "create" | "recover") {
118 const destinationPath =
119 mode === "recover"
120 ? `${serverConfig.environmentIdPath}.recovery`
121 : serverConfig.environmentIdPath;
122 const tempPath = yield* fileSystem.makeTempFileScoped({
123 directory: serverConfig.stateDir,
124 prefix: ".environment-id-",
125 });
126 yield* fileSystem.writeFileString(tempPath, `${value}\n`);
127 // Publish the completed file without replacing an ID created by another process.
128 yield* fileSystem
129 .link(tempPath, destinationPath)
130 .pipe(
131 Effect.catch((cause) =>
132 cause.reason._tag === "AlreadyExists" ? Effect.void : Effect.fail(cause),
133 ),
134 );
135 if (mode === "recover") {
136 // Keep the recovery ID so delayed initializers also publish the same winner.
137 yield* fileSystem.remove(tempPath);
138 yield* fileSystem.copyFile(destinationPath, tempPath);
139 yield* fileSystem.rename(tempPath, serverConfig.environmentIdPath);
140 }
141 },
142 Effect.scoped,
143 Effect.mapError(
144 (cause) =>
145 new ServerEnvironmentIdPersistenceError({
146 operation: "write",
147 environmentIdPath: serverConfig.environmentIdPath,
148 cause,
149 }),
150 ),
151 );
152
153 const environmentIdRaw = yield* Effect.gen(function* () {
154 const persisted = yield* readPersistedEnvironmentId;
155 if (persisted) {
156 return persisted;
157 }
158
159 const generated = yield* crypto.randomUUIDv4;
160 yield* persistEnvironmentId(generated, "create");
161 let winner = yield* readPersistedEnvironmentId;
162 if (winner === null) {
163 yield* persistEnvironmentId(generated, "recover");
164 winner = yield* readPersistedEnvironmentId;
165 }
166 if (winner === null) {
167 return yield* new ServerEnvironmentIdPersistenceError({
168 operation: "initialize",
169 environmentIdPath: serverConfig.environmentIdPath,
170 });
171 }
172 return winner;
173 });
174
175 const environmentId = EnvironmentId.make(environmentIdRaw);
176 return ServerEnvironmentIdentity.of({
177 getEnvironmentId: Effect.succeed(environmentId),
178 });
179});
180
181export const make = Effect.gen(function* () {
182 const path = yield* Path.Path;
183 const serverConfig = yield* ServerConfig.ServerConfig;
184 const secrets = yield* ServerSecretStore.ServerSecretStore;
185 const identity = yield* ServerEnvironmentIdentity;
186 const hostPlatform = yield* HostProcessPlatform;
187 const hostArchitecture = yield* HostProcessArchitecture;
188 const environmentId = yield* identity.getEnvironmentId;
189 const cwdBaseName = path.basename(serverConfig.cwd).trim();
190 const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });
191 const launcher = yield* resolveServiceLauncherMode();
192 const serverSelfUpdate = resolveServerSelfUpdateCapability({
193 desktopManaged: serverConfig.mode === "desktop",
194 launcherManaged: launcher.managed,
195 });
196 // Static is correct: the control fd is known at bootstrap, and the desktop
197 // app and its bundled server ship in one artifact, so a present fd means
198 // the app speaks the requestDesktopUpdate protocol. WSL backends never get
199 // the fd and correctly do not advertise.
200 const desktopAppUpdate =
201 serverSelfUpdate === "desktop-managed" && serverConfig.desktopTelemetryControlFd !== undefined;
202
203 const descriptor: ExecutionEnvironmentDescriptor = {
204 environmentId,
205 label,
206 platform: {
207 os: platformOs(hostPlatform),
208 arch: platformArch(hostArchitecture),
209 },
210 serverVersion: packageJson.version,
211 capabilities: {
212 repositoryIdentity: true,
213 connectionProbe: true,
214 attachmentUploads: true,
215 fileAttachments: { maxUploadBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES },
216 pullRequests: true,
217 threadSettlement: true,
218 threadAutoSettlement: true,
219 threadSnooze: true,
220 environmentThemes: true,
221 threadPinning: true,
222 threadPinReorder: true,
223 threadTitleRegeneration: true,
224 threadPullRequestLinking: true,
225 ...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
226 ...(serverSelfUpdate === "boot-service" || desktopAppUpdate
227 ? {
228 serverSelfUpdateProgress: true,
229 serverUpdateThreadContinuation: true,
230 }
231 : {}),
232 ...(desktopAppUpdate ? { desktopAppUpdate: true } : {}),
233 },
234 };
235
236 return ServerEnvironment.of({
237 getEnvironmentId: Effect.succeed(environmentId),
238 // The publish opt-in and relay link change at runtime (`t3 connect
239 // publish`, the client settings toggle), so the capability is read per
240 // descriptor request rather than baked in at startup.
241 getDescriptor: readAgentActivityPublishingActive(secrets).pipe(
242 Effect.map((agentActivityPublishing) => ({
243 ...descriptor,
244 capabilities: { ...descriptor.capabilities, agentActivityPublishing },
245 })),
246 ),
247 });
248});
249
250export const identityLayer = Layer.effect(ServerEnvironmentIdentity, makeIdentity);
251
252/**
253 * ServerEnvironment is acquired from persisted filesystem and host-process
254 * state. It intentionally has no fallback Layer.succeed value: callers must
255 * provide the external platform services, a ServerConfig, and the
256 * ServerSecretStore backing the descriptor's publishing capability.
257 */
258export const layer = Layer.effect(ServerEnvironment, make).pipe(
259 Layer.provideMerge(identityLayer),
260 Layer.provide(ProcessRunner.layer),
261);