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 Option from "effect/Option";
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 * as ProviderInstanceRegistry from "../provider/Services/ProviderInstanceRegistry.ts";
24import type { ProviderInstance } from "../provider/ProviderDriver.ts";
25import * as TextGeneration from "../textGeneration/TextGeneration.ts";
26import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
27import { detectServerEnvironmentMachineKind } from "./ServerEnvironmentMachine.ts";
28
29export 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
45export 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
53export class ServerEnvironmentIdentity extends Context.Service<
54 ServerEnvironmentIdentity,
55 {
56 readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
57 }
58>()("t3/environment/ServerEnvironment/ServerEnvironmentIdentity") {}
59
60function 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
73function 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
86const makeIdentity = Effect.gen(function* () {
87 const fileSystem = yield* FileSystem.FileSystem;
88 const serverConfig = yield* ServerConfig.ServerConfig;
89 const crypto = yield* Crypto.Crypto;
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
134 .link(tempPath, destinationPath)
135 .pipe(
136 Effect.catch((cause) =>
137 cause.reason._tag === "AlreadyExists" ? Effect.void : Effect.fail(cause),
138 ),
139 );
140 if (mode === "recover") {
141 // Keep the recovery ID so delayed initializers also publish the same winner.
142 yield* fileSystem.remove(tempPath);
143 yield* fileSystem.copyFile(destinationPath, tempPath);
144 yield* fileSystem.rename(tempPath, serverConfig.environmentIdPath);
145 }
146 },
147 Effect.scoped,
148 Effect.mapError(
149 (cause) =>
150 new ServerEnvironmentIdPersistenceError({
151 operation: "write",
152 environmentIdPath: serverConfig.environmentIdPath,
153 cause,
154 }),
155 ),
156 );
157
158 const environmentIdRaw = yield* Effect.gen(function* () {
159 const persisted = yield* readPersistedEnvironmentId;
160 if (persisted) {
161 return persisted;
162 }
163
164 const generated = yield* crypto.randomUUIDv4;
165 yield* persistEnvironmentId(generated, "create");
166 let winner = yield* readPersistedEnvironmentId;
167 if (winner === null) {
168 yield* persistEnvironmentId(generated, "recover");
169 winner = yield* readPersistedEnvironmentId;
170 }
171 if (winner === null) {
172 return yield* new ServerEnvironmentIdPersistenceError({
173 operation: "initialize",
174 environmentIdPath: serverConfig.environmentIdPath,
175 });
176 }
177 return winner;
178 });
179
180 const environmentId = EnvironmentId.make(environmentIdRaw);
181 return ServerEnvironmentIdentity.of({
182 getEnvironmentId: Effect.succeed(environmentId),
183 });
184});
185
186const makeWithProviderRegistry = (
187 providerInstanceRegistry: Option.Option<
188 ProviderInstanceRegistry.ProviderInstanceRegistry["Service"]
189 >,
190) =>
191 Effect.gen(function* () {
192 const path = yield* Path.Path;
193 const serverConfig = yield* ServerConfig.ServerConfig;
194 const secrets = yield* ServerSecretStore.ServerSecretStore;
195 const identity = yield* ServerEnvironmentIdentity;
196 const hostPlatform = yield* HostProcessPlatform;
197 const hostArchitecture = yield* HostProcessArchitecture;
198 const environmentId = yield* identity.getEnvironmentId;
199 const cwdBaseName = path.basename(serverConfig.cwd).trim();
200 const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });
201 const machine = yield* detectServerEnvironmentMachineKind();
202 const launcher = yield* resolveServiceLauncherMode();
203 const serverSelfUpdate = resolveServerSelfUpdateCapability({
204 desktopManaged: serverConfig.mode === "desktop",
205 launcherManaged: launcher.managed,
206 });
207 // Static is correct: the control fd is known at bootstrap, and the desktop
208 // app and its bundled server ship in one artifact, so a present fd means
209 // the app speaks the requestDesktopUpdate protocol. WSL backends never get
210 // the fd and correctly do not advertise.
211 const desktopAppUpdate =
212 serverSelfUpdate === "desktop-managed" &&
213 serverConfig.desktopTelemetryControlFd !== undefined;
214
215 const descriptor: ExecutionEnvironmentDescriptor = {
216 environmentId,
217 label,
218 platform: {
219 os: platformOs(hostPlatform),
220 arch: platformArch(hostArchitecture),
221 ...(machine === null ? {} : { machine }),
222 },
223 serverVersion: packageJson.version,
224 capabilities: {
225 repositoryIdentity: true,
226 connectionProbe: true,
227 attachmentUploads: true,
228 questionAttachments: true,
229 fileAttachments: { maxUploadBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES },
230 pullRequests: true,
231 threadSettlement: true,
232 threadAutoSettlement: true,
233 threadRestartContinuation: true,
234 threadSnooze: true,
235 environmentThemes: true,
236 usageLimitSources: true,
237 usagePriceOverrides: true,
238 threadPinning: true,
239 threadPinReorder: true,
240 threadActiveReorder: true,
241 threadTitleRegeneration: true,
242 threadPullRequests: true,
243 pullRequestStackActions: true,
244 threadPullRequestLinking: true,
245 environmentIcon: true,
246 ...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
247 ...(serverSelfUpdate === "boot-service" || desktopAppUpdate
248 ? {
249 serverSelfUpdateProgress: true,
250 serverUpdateThreadContinuation: true,
251 }
252 : {}),
253 ...(desktopAppUpdate ? { desktopAppUpdate: true } : {}),
254 },
255 };
256
257 return ServerEnvironment.of({
258 getEnvironmentId: Effect.succeed(environmentId),
259 // The publish opt-in and relay link change at runtime (`t3 connect
260 // publish`, the client settings toggle), so the capability is read per
261 // descriptor request rather than baked in at startup.
262 getDescriptor: Effect.gen(function* () {
263 const agentActivityPublishing = yield* readAgentActivityPublishingActive(secrets);
264 const instances = Option.match(providerInstanceRegistry, {
265 onNone: () => Effect.succeed<ReadonlyArray<ProviderInstance>>([]),
266 onSome: (registry) => registry.listInstances,
267 });
268 const threadHandoverGeneration =
269 TextGeneration.findAvailableCodexInstance(yield* instances) !== undefined;
270 return {
271 ...descriptor,
272 capabilities: {
273 ...descriptor.capabilities,
274 agentActivityPublishing,
275 threadHandoverGeneration,
276 },
277 };
278 }),
279 });
280 });
281
282/** @public Service construction is part of the canonical Effect module API. */
283export const make = Effect.gen(function* () {
284 const providerInstanceRegistry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
285 return yield* makeWithProviderRegistry(Option.some(providerInstanceRegistry));
286});
287
288const makeConnectOnly = makeWithProviderRegistry(Option.none());
289
290export const identityLayer = Layer.effect(ServerEnvironmentIdentity, makeIdentity);
291
292/**
293 * ServerEnvironment is acquired from persisted filesystem and host-process
294 * state. It intentionally has no fallback Layer.succeed value: callers must
295 * provide the external platform services, a ServerConfig, and the
296 * ServerSecretStore backing the descriptor's publishing capability.
297 */
298export const layer = Layer.effect(ServerEnvironment, makeConnectOnly).pipe(
299 Layer.provideMerge(identityLayer),
300 Layer.provide(ProcessRunner.layer),
301);
302
303/** Normal server runtime, where provider-backed capabilities must not degrade silently. */
304export const providerRuntimeLayer = Layer.effect(ServerEnvironment, make).pipe(
305 Layer.provideMerge(identityLayer),
306 Layer.provide(ProcessRunner.layer),
307);