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 SecureRandom from "effect/crypto/SecureRandom";
10import * as Deferred from "effect/Deferred";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as Path from "effect/Path";
16import * as Schema from "effect/Schema";
17
18import packageJson from "../../package.json" with { type: "json" };
19import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
20import { resolveServerInstallation } from "../cli/invocation.ts";
21import { readAgentActivityPublishingActive } from "../cloud/config.ts";
22import { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts";
23import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts";
24import * as ServerConfig from "../config.ts";
25import { databaseMigrationHead } from "../persistence/databaseMigrationHead.ts";
26import * as ProcessRunner from "../processRunner.ts";
27import { isSpeechPlatformSupported } from "../speech/platform.ts";
28import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
29import { detectServerEnvironmentMachineKind } from "./ServerEnvironmentMachine.ts";
30
31export class ServerEnvironmentIdPersistenceError extends Schema.TaggedError<ServerEnvironmentIdPersistenceError>()(
32 "ServerEnvironmentIdPersistenceError",
33 {
34 operation: Schema.Literals(["check", "read", "write", "initialize"]),
35 environmentIdPath: Schema.String,
36 cause: Schema.optional(Schema.Defect()),
37 },
38) {
39 override get message(): string {
40 if (this.operation === "initialize") {
41 return `Server environment ID file is missing or empty after initialization at '${this.environmentIdPath}'.`;
42 }
43 return `Server environment ID ${this.operation} failed at '${this.environmentIdPath}'.`;
44 }
45}
46
47export class ServerEnvironment extends Context.Service<
48 ServerEnvironment,
49 {
50 readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
51 readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;
52 }
53>()("t3/environment/ServerEnvironment") {}
54
55export class ServerEnvironmentIdentity extends Context.Service<
56 ServerEnvironmentIdentity,
57 {
58 readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
59 }
60>()("t3/environment/ServerEnvironment/ServerEnvironmentIdentity") {}
61
62function platformOs(platform: NodeJS.Platform): ExecutionEnvironmentDescriptor["platform"]["os"] {
63 switch (platform) {
64 case "darwin":
65 return "darwin";
66 case "linux":
67 return "linux";
68 case "win32":
69 return "windows";
70 default:
71 return "unknown";
72 }
73}
74
75function platformArch(
76 architecture: NodeJS.Architecture,
77): ExecutionEnvironmentDescriptor["platform"]["arch"] {
78 switch (architecture) {
79 case "arm64":
80 return "arm64";
81 case "x64":
82 return "x64";
83 default:
84 return "other";
85 }
86}
87
88const makeIdentity = Effect.gen(function* () {
89 const fileSystem = yield* FileSystem.FileSystem;
90 const serverConfig = yield* ServerConfig.ServerConfig;
91 const random = yield* SecureRandom.SecureRandom;
92
93 const readPersistedEnvironmentId = Effect.gen(function* () {
94 const exists = yield* fileSystem.exists(serverConfig.environmentIdPath).pipe(
95 Effect.mapError(
96 (cause) =>
97 new ServerEnvironmentIdPersistenceError({
98 operation: "check",
99 environmentIdPath: serverConfig.environmentIdPath,
100 cause,
101 }),
102 ),
103 );
104 if (!exists) {
105 return null;
106 }
107
108 const raw = yield* fileSystem.readFileString(serverConfig.environmentIdPath).pipe(
109 Effect.map((value) => value.trim()),
110 Effect.mapError(
111 (cause) =>
112 new ServerEnvironmentIdPersistenceError({
113 operation: "read",
114 environmentIdPath: serverConfig.environmentIdPath,
115 cause,
116 }),
117 ),
118 );
119
120 return raw.length > 0 ? raw : null;
121 });
122
123 const persistEnvironmentId = Effect.fn("ServerEnvironmentIdentity.persistEnvironmentId")(
124 function* (value: string, mode: "create" | "recover") {
125 const destinationPath =
126 mode === "recover"
127 ? `${serverConfig.environmentIdPath}.recovery`
128 : serverConfig.environmentIdPath;
129 const tempPath = yield* fileSystem.makeTempFileScoped({
130 directory: serverConfig.stateDir,
131 prefix: ".environment-id-",
132 });
133 yield* fileSystem.writeFileString(tempPath, `${value}\n`);
134 // Publish the completed file without replacing an ID created by another process.
135 yield* fileSystem.link(tempPath, destinationPath).pipe(
136 Effect.catchIf(
137 (cause) => cause.reason._tag === "AlreadyExists",
138 () => Effect.void,
139 ),
140 );
141 if (mode === "recover") {
142 // Keep the recovery ID so delayed initializers also publish the same winner.
143 yield* fileSystem.remove(tempPath);
144 yield* fileSystem.copyFile(destinationPath, tempPath);
145 yield* fileSystem.rename(tempPath, serverConfig.environmentIdPath);
146 }
147 },
148 Effect.scoped,
149 Effect.mapError(
150 (cause) =>
151 new ServerEnvironmentIdPersistenceError({
152 operation: "write",
153 environmentIdPath: serverConfig.environmentIdPath,
154 cause,
155 }),
156 ),
157 );
158
159 const environmentIdRaw = yield* Effect.gen(function* () {
160 const persisted = yield* readPersistedEnvironmentId;
161 if (persisted) {
162 return persisted;
163 }
164
165 const generated = yield* random.uuidV4();
166 yield* persistEnvironmentId(generated, "create");
167 let winner = yield* readPersistedEnvironmentId;
168 if (winner === null) {
169 yield* persistEnvironmentId(generated, "recover");
170 winner = yield* readPersistedEnvironmentId;
171 }
172 if (winner === null) {
173 return yield* new ServerEnvironmentIdPersistenceError({
174 operation: "initialize",
175 environmentIdPath: serverConfig.environmentIdPath,
176 });
177 }
178 return winner;
179 });
180
181 const environmentId = EnvironmentId.make(environmentIdRaw);
182 return ServerEnvironmentIdentity.of({
183 getEnvironmentId: Effect.succeed(environmentId),
184 });
185});
186
187/** @public */
188export const make = Effect.gen(function* () {
189 const path = yield* Path.Path;
190 const serverConfig = yield* ServerConfig.ServerConfig;
191 const secrets = yield* ServerSecretStore.ServerSecretStore;
192 const identity = yield* ServerEnvironmentIdentity;
193 const hostPlatform = yield* HostProcess.Platform;
194 const hostArchitecture = yield* HostProcess.Architecture;
195 const hostLibc = hostPlatform === "linux" ? yield* HostProcess.LinuxLibc : undefined;
196 const environmentId = yield* identity.getEnvironmentId;
197 const cwdBaseName = path.basename(serverConfig.cwd).trim();
198 const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });
199 const machine = yield* detectServerEnvironmentMachineKind();
200 const launcher = yield* resolveServiceLauncherMode();
201 const serverSelfUpdate = resolveServerSelfUpdateCapability({
202 desktopManaged: serverConfig.mode === "desktop",
203 launcherManaged: launcher.managed,
204 });
205 const serverInstallation = serverSelfUpdate === null ? yield* resolveServerInstallation : null;
206 // The desktop reports whether it can install updates; requests travel over its control fd.
207 const desktopAppUpdate =
208 serverSelfUpdate === "desktop-managed" &&
209 serverConfig.desktopAppUpdate === true &&
210 serverConfig.desktopTelemetryControlFd !== undefined;
211
212 const databaseMigration = databaseMigrationHead(serverConfig.dbPath);
213 const descriptor: ExecutionEnvironmentDescriptor = {
214 environmentId,
215 label,
216 platform: {
217 os: platformOs(hostPlatform),
218 arch: platformArch(hostArchitecture),
219 ...(machine === null ? {} : { machine }),
220 },
221 serverVersion: packageJson.version,
222 orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
223 ...(databaseMigration === undefined ? {} : { databaseMigration }),
224 capabilities: {
225 repositoryIdentity: true,
226 connectionProbe: true,
227 attachmentUploads: true,
228 accessTokenRenewal: true,
229 questionAttachments: true,
230 fileAttachments: { maxUploadBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES },
231 pullRequests: true,
232 pullRequestChecks: true,
233 issues: true,
234 linkedThreadRefreshes: true,
235 issueLinkedThreads: true,
236 issueTrackerAccounts: true,
237 sideChats: true,
238 vcsBranchStatus: true,
239 inlineMessageContext: true,
240 requiredWorktreeBootstrap: true,
241 threadSettlement: true,
242 threadAutoSettlement: true,
243 storageCleanup: true,
244 storageCleanupRun: true,
245 databaseStorage: true,
246 otlpEndpointCheck: true,
247 secretSourceCheck: true,
248 projectWorktreeCleanup: true,
249 settledWorktreeCleanup: true,
250 worktreesDirectory: true,
251 ...(hostPlatform === "darwin" ? { fastWorktreeCheckout: true } : {}),
252 threadAutoSettlementScope: true,
253 threadRestartContinuation: true,
254 projectSettingsOverrides: true,
255 projectProviderInstanceOverrides: true,
256 threadSnooze: true,
257 threadForceStop: true,
258 hostPressure: true,
259 environmentThemes: true,
260 usageLimitSources: true,
261 providerWorkspaceSnapshotsOnDemand: true,
262 modelCatalogRefresh: true,
263 usagePriceOverrides: true,
264 usageModelAliases: true,
265 threadPinning: true,
266 threadPinReorder: true,
267 threadActiveReorder: true,
268 threadAutoSettleOptOut: true,
269 threadProjectFromScratch: true,
270 threadTitleRegeneration: true,
271 commandOutputStreaming: true,
272 threadVisitedTracking: true,
273 threadPullRequests: true,
274 threadPullRequestWatch: true,
275 pullRequestStackActions: true,
276 threadPullRequestLinking: true,
277 serverResolvedCommandContext: true,
278 threadStop: true,
279 ...(hostPlatform === "win32" ? {} : { localServerStop: true }),
280 previewTunnelSetting: true,
281 environmentIcon: true,
282 projectCloneTracking: true,
283 projectOrganization: true,
284 ignoredFileListing: true,
285 ignoredFileSearch: true,
286 triage: true,
287 oneTimeSchedules: true,
288 freshContext: true,
289 scheduledTaskThreadModes: true,
290 npmReleaseLookup: true,
291 voiceTranscription: isSpeechPlatformSupported(hostPlatform, hostArchitecture, hostLibc),
292 cloudVoiceTranscription: true,
293 ...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
294 ...(serverInstallation === null ? {} : { serverInstallation }),
295 ...(serverSelfUpdate === "boot-service" || desktopAppUpdate
296 ? { serverSelfUpdateProgress: true }
297 : {}),
298 ...(serverSelfUpdate === "boot-service" ? { serverUpdateStaging: true } : {}),
299 ...(desktopAppUpdate ? { desktopAppUpdate: true, desktopAppChannelSwitch: true } : {}),
300 serverBrowser: true,
301 peerLinks: true,
302 mcpModeLimitHeader: true,
303 linkFence: true,
304 linkThreadStream: true,
305 linkClientPairing: true,
306 linkPairingForLink: true,
307 mcpApprovalCodes: true,
308 peerLinkPairingCodes: true,
309 mcpHostedApproval: true,
310 shellThreadFamilies: true,
311 shellOlderSettled: true,
312 agentFeedback: true,
313 },
314 };
315
316 // Publishing opt-in and relay links change at runtime (also from the `t3 connect` CLI), so the
317 // capability is read per request. The descriptor is the clients' liveness probe: when file I/O
318 // stalls, answer with the last value read and keep one shared read in flight instead of hanging.
319 const scope = yield* Effect.scope;
320 let lastAgentActivityPublishing = false;
321 let pendingRead: Deferred.Deferred<boolean> | undefined;
322 const startRead = Effect.suspend(() => {
323 if (pendingRead !== undefined) return Effect.succeed(pendingRead);
324 const read = Deferred.makeUnsafe<boolean>();
325 pendingRead = read;
326 return readAgentActivityPublishingActive(secrets).pipe(
327 Effect.tap((active) =>
328 Effect.sync(() => {
329 lastAgentActivityPublishing = active;
330 }),
331 ),
332 Effect.ensuring(
333 Effect.sync(() => {
334 pendingRead = undefined;
335 }),
336 ),
337 Deferred.into(read),
338 Effect.forkIn(scope),
339 Effect.as(read),
340 );
341 }).pipe(Effect.uninterruptible);
342 const agentActivityPublishing = startRead.pipe(
343 Effect.flatMap((read) => Deferred.await(read).pipe(Effect.timeoutOption("1 second"))),
344 Effect.map(Option.getOrElse(() => lastAgentActivityPublishing)),
345 );
346
347 return ServerEnvironment.of({
348 getEnvironmentId: Effect.succeed(environmentId),
349 getDescriptor: agentActivityPublishing.pipe(
350 Effect.map((agentActivityPublishing) => ({
351 ...descriptor,
352 capabilities: { ...descriptor.capabilities, agentActivityPublishing },
353 })),
354 ),
355 });
356});
357
358export const layerIdentity = Layer.effect(ServerEnvironmentIdentity, makeIdentity);
359
360export const layer = Layer.effect(ServerEnvironment, make).pipe(
361 Layer.provideMerge(layerIdentity),
362 Layer.provide(ProcessRunner.layer),
363);