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