Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ServerEnvironment.ts

283 lines10.1 KB

1import {
2 EnvironmentId,
3 ORCHESTRATION_PROTOCOL_VERSION,
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 }
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 }
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 }
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.link(tempPath, destinationPath).pipe(
131 Effect.catchIf(
132 (cause) => cause.reason._tag === "AlreadyExists",
133 () => Effect.void,
134 ),
135 );
136 if (mode === "recover") {
137 // Keep the recovery ID so delayed initializers also publish the same winner.
138 yield* fileSystem.remove(tempPath);
139 yield* fileSystem.copyFile(destinationPath, tempPath);
140 yield* fileSystem.rename(tempPath, serverConfig.environmentIdPath);
141 }
142 },
143 Effect.scoped,
144 Effect.mapError(
145 (cause) =>
146 new ServerEnvironmentIdPersistenceError({
147 operation: "write",
148 environmentIdPath: serverConfig.environmentIdPath,
149 cause,
150 }),
151 ),
152 );
153​
154 const environmentIdRaw = yield* Effect.gen(function* () {
155 const persisted = yield* readPersistedEnvironmentId;
156 if (persisted) {
157 return persisted;
158 }
159​
160 const generated = yield* crypto.randomUUIDv4;
161 yield* persistEnvironmentId(generated, "create");
162 let winner = yield* readPersistedEnvironmentId;
163 if (winner === null) {
164 yield* persistEnvironmentId(generated, "recover");
165 winner = yield* readPersistedEnvironmentId;
166 }
167 if (winner === null) {
168 return yield* new ServerEnvironmentIdPersistenceError({
169 operation: "initialize",
170 environmentIdPath: serverConfig.environmentIdPath,
171 });
172 }
173 return winner;
174 });
175​
176 const environmentId = EnvironmentId.make(environmentIdRaw);
177 return ServerEnvironmentIdentity.of({
178 getEnvironmentId: Effect.succeed(environmentId),
179 });
180});
181​
182/** @public Service construction is part of the canonical Effect module API. */
183export const make = Effect.gen(function* () {
184 const path = yield* Path.Path;
185 const serverConfig = yield* ServerConfig.ServerConfig;
186 const secrets = yield* ServerSecretStore.ServerSecretStore;
187 const identity = yield* ServerEnvironmentIdentity;
188 const hostPlatform = yield* HostProcessPlatform;
189 const hostArchitecture = yield* HostProcessArchitecture;
190 const environmentId = yield* identity.getEnvironmentId;
191 const cwdBaseName = path.basename(serverConfig.cwd).trim();
192 const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });
193 const machine = yield* detectServerEnvironmentMachineKind();
194 const launcher = yield* resolveServiceLauncherMode();
195 const serverSelfUpdate = resolveServerSelfUpdateCapability({
196 desktopManaged: serverConfig.mode === "desktop",
197 launcherManaged: launcher.managed,
198 });
199 // Static is correct: the control fd is known at bootstrap, and the desktop
200 // app and its bundled server ship in one artifact, so a present fd means
201 // the app speaks the requestDesktopUpdate protocol. WSL backends never get
202 // the fd and correctly do not advertise.
203 const desktopAppUpdate =
204 serverSelfUpdate === "desktop-managed" && serverConfig.desktopTelemetryControlFd !== undefined;
205​
206 const descriptor: ExecutionEnvironmentDescriptor = {
207 environmentId,
208 label,
209 platform: {
210 os: platformOs(hostPlatform),
211 arch: platformArch(hostArchitecture),
212 ...(machine === null ? {} : { machine }),
213 },
214 serverVersion: packageJson.version,
215 orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
216 capabilities: {
217 repositoryIdentity: true,
218 connectionProbe: true,
219 attachmentUploads: true,
220 questionAttachments: true,
221 fileAttachments: { maxUploadBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES },
222 pullRequests: true,
223 pullRequestChecks: true,
224 inlineMessageContext: true,
225 requiredWorktreeBootstrap: true,
226 threadSettlement: true,
227 threadAutoSettlement: true,
228 storageCleanup: true,
229 projectWorktreeCleanup: true,
230 threadRestartContinuation: true,
231 projectSettingsOverrides: true,
232 threadSnooze: true,
233 environmentThemes: true,
234 usageLimitSources: true,
235 usagePriceOverrides: true,
236 threadPinning: true,
237 threadPinReorder: true,
238 threadActiveReorder: true,
239 threadAutoSettleOptOut: true,
240 threadTitleRegeneration: true,
241 threadVisitedTracking: true,
242 threadPullRequests: true,
243 pullRequestStackActions: true,
244 threadPullRequestLinking: true,
245 serverResolvedCommandContext: true,
246 environmentIcon: true,
247 projectCloneTracking: true,
248 ...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
249 // V2 restart recovery uses the environment-owned opt-in. The old
250 // per-update request flag is not wired into the V2 update RPC path.
251 ...(serverSelfUpdate === "boot-service" || desktopAppUpdate
252 ? { serverSelfUpdateProgress: true }
253 : {}),
254 ...(desktopAppUpdate ? { desktopAppUpdate: true } : {}),
255 },
256 };
257​
258 return ServerEnvironment.of({
259 getEnvironmentId: Effect.succeed(environmentId),
260 // The publish opt-in and relay link change at runtime (`t3 connect
261 // publish`, the client settings toggle), so the capability is read per
262 // descriptor request rather than baked in at startup.
263 getDescriptor: readAgentActivityPublishingActive(secrets).pipe(
264 Effect.map((agentActivityPublishing) => ({
265 ...descriptor,
266 capabilities: { ...descriptor.capabilities, agentActivityPublishing },
267 })),
268 ),
269 });
270});
271​
272export const identityLayer = Layer.effect(ServerEnvironmentIdentity, makeIdentity);
273​
274/**
275 * ServerEnvironment is acquired from persisted filesystem and host-process
276 * state. It intentionally has no fallback Layer.succeed value: callers must
277 * provide the external platform services, a ServerConfig, and the
278 * ServerSecretStore backing the descriptor's publishing capability.
279 */
280export const layer = Layer.effect(ServerEnvironment, make).pipe(
281 Layer.provideMerge(identityLayer),
282 Layer.provide(ProcessRunner.layer),
283);