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