The best way to control Claude Code, Codex and more from any computer or phone

main
ts 502 lines 16.4 KB
Raw
1 import * as Effect from "effect/Effect";
2 import { msg } from "gt-react";
3 import * as Option from "effect/Option";
4 import * as Schema from "effect/Schema";
5 import * as Stream from "effect/Stream";
6 import * as SubscriptionRef from "effect/SubscriptionRef";
7 import type { HttpClient } from "effect/http";
8 import {
9 EnvironmentCloudEndpointUnavailableError,
10 type EnvironmentCloudLinkStateResult,
11 type EnvironmentConnectReachability,
12 EnvironmentHttpBadRequestError,
13 EnvironmentHttpConflictError,
14 EnvironmentHttpForbiddenError,
15 EnvironmentHttpInternalServerError,
16 EnvironmentHttpUnauthorizedError,
17 EnvironmentId,
18 WS_METHODS,
19 } from "@t3tools/contracts";
20 import {
21 type RelayEnvironmentLinkResponse,
22 type RelayManagedEndpointProviderKind,
23 } from "@t3tools/contracts/relay";
24 import { EnvironmentRegistry, EnvironmentSupervisor } from "@t3tools/client-runtime/connection";
25 import { request, runStream } from "@t3tools/client-runtime/rpc";
26 import { ManagedRelay, relayRequestFailureDetail } from "@t3tools/client-runtime/relay";
27 import { executeConnectedEnvironmentHttpRequest } from "@t3tools/client-runtime/state/environmentHttpAuth";
28
29 import { m } from "../i18n/messages";
30 import { resolveCloudPublicConfig } from "./publicConfig";
31 import {
32 finishRelayClientInstall,
33 reportRelayClientInstallProgress,
34 requestRelayClientInstallConfirmation,
35 } from "./relayClientInstallDialog";
36
37 function relayUrl(): string | null {
38 return resolveCloudPublicConfig().relayUrl;
39 }
40
41 export class CloudEnvironmentLinkError extends Schema.TaggedError<CloudEnvironmentLinkError>()(
42 "CloudEnvironmentLinkError",
43 {
44 message: Schema.String,
45 cause: Schema.optional(Schema.Defect()),
46 traceId: Schema.optional(Schema.String),
47 },
48 ) {}
49
50 export const isCloudEnvironmentLinkError = Schema.is(CloudEnvironmentLinkError);
51
52 const relayClientRpcError = (message: string) => (cause: unknown) =>
53 new CloudEnvironmentLinkError({
54 message,
55 cause,
56 });
57
58 const ensureRelayClientAvailable = Effect.fn("linkEnvironment.ensureRelayClientAvailable")(
59 function* (
60 environmentId: EnvironmentId,
61 ): Effect.fn.Return<void, CloudEnvironmentLinkError, EnvironmentRegistry.EnvironmentRegistry> {
62 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
63 const status = yield* registry
64 .run(environmentId, request(WS_METHODS.cloudGetRelayClientStatus, {}))
65 .pipe(
66 Effect.mapError(relayClientRpcError(m(msg("Could not check relay client availability.")))),
67 );
68 if (status.status === "available") return;
69 if (status.status === "unsupported") {
70 return yield* new CloudEnvironmentLinkError({
71 message: m(
72 msg("T3 Code cannot install the relay client automatically on {platform}-{arch}.", {
73 platform: status.platform,
74 arch: status.arch,
75 }),
76 ),
77 });
78 }
79
80 const confirmed = yield* Effect.tryPromise({
81 try: () => requestRelayClientInstallConfirmation(status.version),
82 catch: relayClientRpcError(m(msg("Could not confirm relay client installation."))),
83 });
84 if (!confirmed) {
85 return yield* new CloudEnvironmentLinkError({
86 message: m(msg("Relay client installation was cancelled.")),
87 });
88 }
89
90 const installed = yield* registry
91 .runStream(
92 environmentId,
93 runStream(WS_METHODS.cloudInstallRelayClient, {}).pipe(
94 Stream.tap((event) => Effect.sync(() => reportRelayClientInstallProgress(event))),
95 ),
96 )
97 .pipe(
98 Stream.runLast,
99 Effect.mapError(relayClientRpcError(m(msg("Could not install the relay client.")))),
100 Effect.ensuring(Effect.sync(finishRelayClientInstall)),
101 );
102 if (Option.isNone(installed) || installed.value.type !== "complete") {
103 return yield* new CloudEnvironmentLinkError({
104 message: m(msg("The relay client install completed without a final status.")),
105 });
106 }
107 const installedStatus = installed.value.status;
108 if (installedStatus.status !== "available") {
109 return yield* new CloudEnvironmentLinkError({
110 message:
111 installedStatus.status === "unsupported"
112 ? m(
113 msg("T3 Code cannot install the relay client automatically on {platform}-{arch}.", {
114 platform: installedStatus.platform,
115 arch: installedStatus.arch,
116 }),
117 )
118 : m(msg("The relay client is still unavailable after installation.")),
119 });
120 }
121 },
122 );
123
124 const isEnvironmentCloudApiError = Schema.is(
125 Schema.Union([
126 EnvironmentHttpBadRequestError,
127 EnvironmentHttpUnauthorizedError,
128 EnvironmentHttpForbiddenError,
129 EnvironmentHttpConflictError,
130 EnvironmentHttpInternalServerError,
131 EnvironmentCloudEndpointUnavailableError,
132 ]),
133 );
134
135 function decodedRelayClientError(message: string) {
136 return (cause: ManagedRelay.ManagedRelayClientError) => {
137 const failed = cause._tag === "ManagedRelayRequestFailedError" ? cause : undefined;
138 const traceId = "traceId" in cause ? cause.traceId : undefined;
139 const detail = (failed && relayRequestFailureDetail(failed)) ?? cause.message;
140 return new CloudEnvironmentLinkError({
141 message: detail ? m(msg("{message}: {detail}", { message, detail })) : message,
142 cause,
143 ...(traceId ? { traceId } : {}),
144 });
145 };
146 }
147
148 function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
149 if (isEnvironmentCloudApiError(cause)) {
150 return cause;
151 }
152 if (typeof cause !== "object" || cause === null) {
153 return null;
154 }
155 return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;
156 }
157
158 /** `msg()` sentences: the failure alone, and the same failure followed by the server's `{detail}`. */
159 interface EnvironmentFailureCopy {
160 readonly message: string;
161 readonly withDetail: string;
162 }
163
164 const environmentApiError = (copy: EnvironmentFailureCopy) => (cause: unknown) => {
165 const environmentError = findEnvironmentCloudApiError(cause);
166 return new CloudEnvironmentLinkError({
167 message: environmentError
168 ? m(copy.withDetail, { detail: environmentError.message })
169 : m(copy.message),
170 cause,
171 });
172 };
173
174 function endpointOrigin(httpBaseUrl: string) {
175 const url = new URL(httpBaseUrl);
176 return {
177 localHttpHost: "127.0.0.1",
178 localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
179 };
180 }
181
182 const MANAGED_ENDPOINT_PROVIDER_KIND =
183 "cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;
184
185 function ensureLinkedEnvironmentMatches(input: {
186 readonly expectedEnvironmentId: string;
187 readonly expectedProviderKind: RelayManagedEndpointProviderKind;
188 readonly link: RelayEnvironmentLinkResponse;
189 }): Effect.Effect<void, CloudEnvironmentLinkError> {
190 if (input.link.environmentId !== input.expectedEnvironmentId) {
191 return new CloudEnvironmentLinkError({
192 message: m(msg("Relay returned credentials for a different environment.")),
193 });
194 }
195 if (input.link.endpoint.providerKind !== input.expectedProviderKind) {
196 return new CloudEnvironmentLinkError({
197 message: m(msg("Relay returned credentials for a different endpoint provider.")),
198 });
199 }
200 return Effect.void;
201 }
202
203 export interface CloudLinkTarget {
204 readonly environmentId: EnvironmentId;
205 }
206
207 export type CloudLinkState = EnvironmentCloudLinkStateResult;
208
209 // Linking can install the relay client and start a managed tunnel before it answers.
210 const CLOUD_LINK_REQUEST_TIMEOUT_MS = 60_000;
211
212 type ConnectedEnvironmentHttpRequest<A, E, R> = Parameters<
213 typeof executeConnectedEnvironmentHttpRequest<"connect", A, E, R>
214 >[0];
215
216 /** Runs on the target environment with this client's own credentials for it. */
217 const connectRequest = <A, E, R>(
218 target: CloudLinkTarget,
219 input: Omit<ConnectedEnvironmentHttpRequest<A, E, R>, "group" | "timeoutMs">,
220 failure: EnvironmentFailureCopy,
221 ) =>
222 Effect.flatMap(EnvironmentRegistry.EnvironmentRegistry, (registry) =>
223 registry.run(
224 target.environmentId,
225 executeConnectedEnvironmentHttpRequest({
226 ...input,
227 group: "connect",
228 timeoutMs: CLOUD_LINK_REQUEST_TIMEOUT_MS,
229 }),
230 ),
231 ).pipe(Effect.mapError(environmentApiError(failure)));
232
233 const preparedEndpoint = (target: CloudLinkTarget) =>
234 Effect.flatMap(EnvironmentRegistry.EnvironmentRegistry, (registry) =>
235 registry.run(
236 target.environmentId,
237 Effect.flatMap(EnvironmentSupervisor.EnvironmentSupervisor, (supervisor) =>
238 SubscriptionRef.get(supervisor.prepared),
239 ),
240 ),
241 ).pipe(
242 Effect.mapError(
243 environmentApiError({
244 message: msg("Could not reach the environment."),
245 withDetail: msg("Could not reach the environment: {detail}"),
246 }),
247 ),
248 Effect.flatMap(
249 Option.match({
250 onNone: () =>
251 Effect.fail(
252 new CloudEnvironmentLinkError({ message: m(msg("The environment is not connected.")) }),
253 ),
254 onSome: ({ httpBaseUrl, target }) =>
255 Effect.succeed({
256 httpBaseUrl,
257 wsBaseUrl:
258 target._tag === "PrimaryConnectionTarget"
259 ? target.wsBaseUrl
260 : httpBaseUrl.replace(/^http/, "ws"),
261 }),
262 }),
263 ),
264 );
265
266 type CloudLinkServices = EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient;
267
268 export const readCloudLinkState: (input: {
269 readonly target: CloudLinkTarget;
270 }) => Effect.Effect<CloudLinkState | null, CloudEnvironmentLinkError, CloudLinkServices> =
271 Effect.fn("linkEnvironment.readCloudLinkState")(function* (input: {
272 readonly target: CloudLinkTarget;
273 }) {
274 return yield* connectRequest(
275 input.target,
276 {
277 method: "GET",
278 url: (urls) => urls.linkState(),
279 request: ({ client, headers }) => client.linkState({ headers }),
280 },
281 {
282 message: msg("Could not read environment cloud link state."),
283 withDetail: msg("Could not read environment cloud link state: {detail}"),
284 },
285 );
286 });
287
288 /** Runs the environment's T3 Connect reachability check now; the link state then reports it. */
289 export const checkCloudReachability: (input: {
290 readonly target: CloudLinkTarget;
291 }) => Effect.Effect<EnvironmentConnectReachability, CloudEnvironmentLinkError, CloudLinkServices> =
292 Effect.fn("linkEnvironment.checkCloudReachability")(function* (input: {
293 readonly target: CloudLinkTarget;
294 }) {
295 return yield* connectRequest(
296 input.target,
297 {
298 method: "POST",
299 url: (urls) => urls.checkReachability(),
300 request: ({ client, headers }) => client.checkReachability({ headers }),
301 },
302 {
303 message: msg("Could not check T3 Connect."),
304 withDetail: msg("Could not check T3 Connect: {detail}"),
305 },
306 );
307 });
308
309 export const updateCloudPreferences: (input: {
310 readonly target: CloudLinkTarget;
311 readonly publishAgentActivity: boolean;
312 readonly holdWebhooksWhileOffline?: boolean;
313 }) => Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, CloudLinkServices> = Effect.fn(
314 "linkEnvironment.updateCloudPreferences",
315 )(function* (input: {
316 readonly target: CloudLinkTarget;
317 readonly publishAgentActivity: boolean;
318 readonly holdWebhooksWhileOffline?: boolean;
319 }) {
320 const { target, ...payload } = input;
321 return yield* connectRequest(
322 target,
323 {
324 method: "POST",
325 url: (urls) => urls.preferences(),
326 request: ({ client, headers }) => client.preferences({ headers, payload }),
327 },
328 {
329 message: msg("Could not update environment cloud preferences."),
330 withDetail: msg("Could not update environment cloud preferences: {detail}"),
331 },
332 );
333 });
334
335 export const unlinkEnvironmentFromCloud: (input: {
336 readonly target: CloudLinkTarget;
337 readonly clerkToken: string | null;
338 }) => Effect.Effect<
339 void,
340 CloudEnvironmentLinkError,
341 CloudLinkServices | ManagedRelay.ManagedRelayClient
342 > = Effect.fn("linkEnvironment.unlinkEnvironmentFromCloud")(function* (input: {
343 readonly target: CloudLinkTarget;
344 readonly clerkToken: string | null;
345 }) {
346 yield* connectRequest(
347 input.target,
348 {
349 method: "POST",
350 url: (urls) => urls.unlink(),
351 request: ({ client, headers }) => client.unlink({ headers }),
352 },
353 {
354 message: msg("Could not unlink the environment from cloud."),
355 withDetail: msg("Could not unlink the environment from cloud: {detail}"),
356 },
357 );
358
359 const configuredRelayUrl = relayUrl();
360 if (configuredRelayUrl && input.clerkToken) {
361 const relayClient = yield* ManagedRelay.ManagedRelayClient;
362 yield* relayClient
363 .unlinkEnvironment({
364 clerkToken: input.clerkToken,
365 environmentId: input.target.environmentId,
366 })
367 .pipe(
368 Effect.mapError(
369 decodedRelayClientError(
370 m(
371 msg(
372 "Disconnected locally, but T3 Connect did not confirm it removed this environment",
373 ),
374 ),
375 ),
376 ),
377 );
378 }
379 });
380
381 export type CloudLinkMode = "managed" | "publish_only";
382
383 const PUBLISH_ONLY_PROVIDER_KIND = "manual" satisfies RelayManagedEndpointProviderKind;
384
385 export const linkEnvironmentToCloud: (input: {
386 readonly target: CloudLinkTarget;
387 readonly clerkToken: string;
388 readonly mode?: CloudLinkMode;
389 }) => Effect.Effect<
390 void,
391 CloudEnvironmentLinkError,
392 CloudLinkServices | ManagedRelay.ManagedRelayClient
393 > = Effect.fn("linkEnvironment.linkEnvironmentToCloud")(function* (input: {
394 readonly target: CloudLinkTarget;
395 readonly clerkToken: string;
396 readonly mode?: CloudLinkMode;
397 }) {
398 const configuredRelayUrl = relayUrl();
399 if (!configuredRelayUrl) {
400 return yield* new CloudEnvironmentLinkError({
401 message: m(msg("{name} is not configured.", { name: "T3CODE_RELAY_URL" })),
402 });
403 }
404 const managedTunnelsEnabled = (input.mode ?? "managed") === "managed";
405 const providerKind = managedTunnelsEnabled
406 ? MANAGED_ENDPOINT_PROVIDER_KIND
407 : PUBLISH_ONLY_PROVIDER_KIND;
408 const relayClient = yield* ManagedRelay.ManagedRelayClient;
409 // The environment only signs a proof for the loopback origin this request reaches it on.
410 const endpoint = yield* preparedEndpoint(input.target);
411 if (managedTunnelsEnabled) {
412 yield* ensureRelayClientAvailable(input.target.environmentId);
413 }
414
415 const challenge = yield* relayClient
416 .createEnvironmentLinkChallenge({
417 clerkToken: input.clerkToken,
418 payload: {
419 notificationsEnabled: true,
420 liveActivitiesEnabled: true,
421 managedTunnelsEnabled,
422 },
423 })
424 .pipe(
425 Effect.mapError(
426 decodedRelayClientError(
427 m(
428 msg("{url} failed", {
429 url: `${configuredRelayUrl}/v1/client/environment-link-challenges`,
430 }),
431 ),
432 ),
433 ),
434 );
435 const proof = yield* connectRequest(
436 input.target,
437 {
438 method: "POST",
439 url: (urls) => urls.linkProof(),
440 request: ({ client, headers }) =>
441 client.linkProof({
442 headers,
443 payload: {
444 challenge: challenge.challenge,
445 relayIssuer: configuredRelayUrl,
446 endpoint: { ...endpoint, providerKind },
447 origin: endpointOrigin(endpoint.httpBaseUrl),
448 },
449 }),
450 },
451 {
452 message: msg("Could not obtain environment link proof."),
453 withDetail: msg("Could not obtain environment link proof: {detail}"),
454 },
455 );
456 const link = yield* relayClient
457 .linkEnvironment({
458 clerkToken: input.clerkToken,
459 payload: {
460 proof,
461 notificationsEnabled: true,
462 liveActivitiesEnabled: true,
463 managedTunnelsEnabled,
464 },
465 })
466 .pipe(
467 Effect.mapError(
468 decodedRelayClientError(
469 m(msg("{url} failed", { url: `${configuredRelayUrl}/v1/client/environment-links` })),
470 ),
471 ),
472 );
473 yield* ensureLinkedEnvironmentMatches({
474 expectedEnvironmentId: input.target.environmentId,
475 expectedProviderKind: providerKind,
476 link,
477 });
478
479 yield* connectRequest(
480 input.target,
481 {
482 method: "POST",
483 url: (urls) => urls.relayConfig(),
484 request: ({ client, headers }) =>
485 client.relayConfig({
486 headers,
487 payload: {
488 relayUrl: configuredRelayUrl,
489 relayIssuer: link.relayIssuer,
490 cloudUserId: link.cloudUserId,
491 environmentCredential: link.environmentCredential,
492 cloudMintPublicKey: link.cloudMintPublicKey,
493 endpointRuntime: link.endpointRuntime,
494 },
495 }),
496 },
497 {
498 message: msg("Could not configure environment relay access."),
499 withDetail: msg("Could not configure environment relay access: {detail}"),
500 },
501 );
502 });