@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 135 lines 5.35 KB
Raw
1 import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
2 import type { RemoteEnvironmentRequestError } from "@t3tools/client-runtime/rpc";
3 import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
4 import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapToken";
5 import * as Clock from "effect/Clock";
6 import * as Context from "effect/Context";
7 import * as Duration from "effect/Duration";
8 import * as Mac from "effect/crypto/Mac";
9 import * as Effect from "effect/Effect";
10 import * as Layer from "effect/Layer";
11 import * as Option from "effect/Option";
12 import * as Ref from "effect/Ref";
13 import * as Schedule from "effect/Schedule";
14 import * as Schema from "effect/Schema";
15 import * as Semaphore from "effect/Semaphore";
16 import * as HttpClient from "effect/http/HttpClient";
17
18 import * as DesktopBackendPool from "./DesktopBackendPool.ts";
19
20 // Each /oauth/token attempt may take 10 s, so a backend busy after ready needs several attempts.
21 const BOOTSTRAP_TRANSIENT_RETRY_TIMEOUT = Duration.seconds(60);
22 const BOOTSTRAP_TRANSIENT_RETRY_INTERVAL = Duration.millis(500);
23 const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
24
25 const isTransientBearerBootstrapError = (error: RemoteEnvironmentRequestError): boolean => {
26 switch (error._tag) {
27 case "RemoteEnvironmentAuthFetchError":
28 case "RemoteEnvironmentAuthTimeoutError":
29 return true;
30 case "RemoteEnvironmentAuthUndeclaredStatusError":
31 return TRANSIENT_BOOTSTRAP_STATUS_CODES.has(error.status);
32 default:
33 return false;
34 }
35 };
36
37 export class DesktopLocalEnvironmentAuthBackendNotConfiguredError extends Schema.TaggedError<DesktopLocalEnvironmentAuthBackendNotConfiguredError>()(
38 "DesktopLocalEnvironmentAuthBackendNotConfiguredError",
39 {},
40 ) {
41 override get message(): string {
42 return "Local backend is not configured.";
43 }
44 }
45
46 export class DesktopLocalEnvironmentAuthSessionBootstrapError extends Schema.TaggedError<DesktopLocalEnvironmentAuthSessionBootstrapError>()(
47 "DesktopLocalEnvironmentAuthSessionBootstrapError",
48 { cause: Schema.Defect() },
49 ) {
50 override get message(): string {
51 return "Failed to create the local desktop bearer session.";
52 }
53 }
54
55 export const DesktopLocalEnvironmentAuthError = Schema.Union([
56 DesktopLocalEnvironmentAuthBackendNotConfiguredError,
57 DesktopLocalEnvironmentAuthSessionBootstrapError,
58 ]);
59 export type DesktopLocalEnvironmentAuthError = typeof DesktopLocalEnvironmentAuthError.Type;
60
61 export class DesktopLocalEnvironmentAuth extends Context.Service<
62 DesktopLocalEnvironmentAuth,
63 {
64 readonly getBearerToken: Effect.Effect<string, DesktopLocalEnvironmentAuthError>;
65 }
66 >()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
67
68 /** @public */
69 export const make = Effect.gen(function* () {
70 const pool = yield* DesktopBackendPool.DesktopBackendPool;
71 const httpClient = yield* HttpClient.HttpClient;
72 const mac = yield* Mac.Mac;
73 const tokenRef = yield* Ref.make(Option.none<string>());
74 const mutex = yield* Semaphore.make(1);
75
76 const getBearerToken = mutex
77 .withPermits(1)(
78 Effect.gen(function* () {
79 const cached = yield* Ref.get(tokenRef);
80 if (Option.isSome(cached)) {
81 return cached.value;
82 }
83
84 const instances = yield* pool.list;
85 const primary = instances.find((instance) => instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
86 if (primary === undefined || !(yield* primary.waitForReady(Duration.infinity))) {
87 return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
88 }
89 const configOption = yield* primary.currentConfig;
90 if (Option.isNone(configOption)) {
91 return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
92 }
93 const config = configOption.value;
94 // Secret-authenticated backends accept the current window token; the launch token may be stale.
95 const secret = config.bootstrap.desktopBootstrapSecret;
96 const credential =
97 secret === undefined
98 ? config.bootstrap.desktopBootstrapToken
99 : yield* currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis).pipe(
100 Effect.provideService(Mac.Mac, mac),
101 );
102 if (!credential) {
103 return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
104 }
105 const session = yield* bootstrapRemoteBearerSession({
106 httpBaseUrl: config.httpBaseUrl.href,
107 credential,
108 clientMetadata: {
109 label: "T3 Code Desktop",
110 deviceType: "desktop",
111 },
112 }).pipe(
113 Effect.provideService(HttpClient.HttpClient, httpClient),
114 Effect.retry({
115 while: isTransientBearerBootstrapError,
116 schedule: Schedule.spaced(BOOTSTRAP_TRANSIENT_RETRY_INTERVAL),
117 }),
118 Effect.timeout(BOOTSTRAP_TRANSIENT_RETRY_TIMEOUT),
119 Effect.mapError(
120 (cause) =>
121 new DesktopLocalEnvironmentAuthSessionBootstrapError({
122 cause,
123 }),
124 ),
125 );
126 yield* Ref.set(tokenRef, Option.some(session.access_token));
127 return session.access_token;
128 }),
129 )
130 .pipe(Effect.withSpan("desktop.localEnvironmentAuth.getBearerToken"));
131
132 return DesktopLocalEnvironmentAuth.of({ getBearerToken });
133 });
134
135 export const layer = Layer.effect(DesktopLocalEnvironmentAuth, make);