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