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
| 1 | import { pipe } from "effect/Function"; |
| 2 | import { |
| 3 | type AuthEnvironmentScope, |
| 4 | AuthSessionState, |
| 5 | EnvironmentAuthInvalidError, |
| 6 | type EnvironmentId, |
| 7 | EnvironmentOperationForbiddenError, |
| 8 | EnvironmentScopeRequiredError, |
| 9 | type ServerConfig, |
| 10 | sessionGrantsScope, |
| 11 | } from "@t3tools/contracts"; |
| 12 | import * as Cause from "effect/Cause"; |
| 13 | import * as Effect from "effect/Effect"; |
| 14 | import * as Option from "effect/Option"; |
| 15 | import * as Schema from "effect/Schema"; |
| 16 | import * as Stream from "effect/Stream"; |
| 17 | import * as SubscriptionRef from "effect/SubscriptionRef"; |
| 18 | import { HttpClient } from "effect/http"; |
| 19 | import { AsyncResult, Atom } from "effect/reactivity"; |
| 20 | |
| 21 | import * as RemoteEnvironmentAuthorization from "../authorization/service.ts"; |
| 22 | import * as EnvironmentRegistry from "../connection/registry.ts"; |
| 23 | import type { PreparedConnection } from "../connection/model.ts"; |
| 24 | import * as EnvironmentSupervisor from "../connection/supervisor.ts"; |
| 25 | import * as ManagedRelay from "../relay/managedRelay.ts"; |
| 26 | import { |
| 27 | RemoteEnvironmentAuthFetchError, |
| 28 | RemoteEnvironmentAuthUndeclaredStatusError, |
| 29 | type RemoteEnvironmentRequestError, |
| 30 | } from "../rpc/http.ts"; |
| 31 | import type { RpcSession } from "../rpc/session.ts"; |
| 32 | import { safeErrorLogAttributes } from "../errors/safeLog.ts"; |
| 33 | import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts"; |
| 34 | import { followStreamInEnvironment } from "./environmentStreams.ts"; |
| 35 | |
| 36 | /** @public Required to name the error in consumers' inferred session results. */ |
| 37 | export class SessionHttpClientUnavailable extends Schema.TaggedError<SessionHttpClientUnavailable>()( |
| 38 | "SessionHttpClientUnavailable", |
| 39 | {}, |
| 40 | ) {} |
| 41 | |
| 42 | function initialConfigOption<E>( |
| 43 | initialConfig: Effect.Effect<ServerConfig, E>, |
| 44 | ): Effect.Effect<Option.Option<ServerConfig>> { |
| 45 | return initialConfig.pipe( |
| 46 | Effect.asSome, |
| 47 | Effect.catch((error) => |
| 48 | Effect.logWarning("Could not load the initial environment configuration.").pipe( |
| 49 | Effect.annotateLogs({ ...safeErrorLogAttributes(error) }), |
| 50 | Effect.as(Option.none<ServerConfig>()), |
| 51 | ), |
| 52 | ), |
| 53 | ); |
| 54 | } |
| 55 | |
| 56 | const DEFAULT_SESSION_STATE_TIMEOUT_MS = 6_000; |
| 57 | const MAX_SESSION_STATE_TIMEOUT_MS = 60_000; |
| 58 | const SESSION_STATE_RETRY_BASE_MS = 2_000; |
| 59 | const SESSION_STATE_RETRY_MAX_MS = 60_000; |
| 60 | |
| 61 | const isSessionRejectionError = Schema.is( |
| 62 | Schema.Union([ |
| 63 | EnvironmentAuthInvalidError, |
| 64 | EnvironmentScopeRequiredError, |
| 65 | EnvironmentOperationForbiddenError, |
| 66 | ]), |
| 67 | ); |
| 68 | const isSessionResponse = Schema.is(AuthSessionState); |
| 69 | const isUndeclaredStatusError = Schema.is(RemoteEnvironmentAuthUndeclaredStatusError); |
| 70 | const isAuthFetchError = Schema.is(RemoteEnvironmentAuthFetchError); |
| 71 | |
| 72 | /** |
| 73 | * True only when the host said no: its session lacks the scope, or it rejected the credential. |
| 74 | * A lookup that is still pending or failed on the network is not a denial. |
| 75 | */ |
| 76 | export function sessionDeniesScope( |
| 77 | result: AsyncResult.AsyncResult<AuthSessionState, unknown>, |
| 78 | scope: AuthEnvironmentScope, |
| 79 | ): boolean { |
| 80 | if (result._tag === "Success") return !sessionGrantsScope(result.value, scope); |
| 81 | return result._tag === "Failure" && isSessionRejection(result.cause); |
| 82 | } |
| 83 | |
| 84 | function isSessionRejection(cause: Cause.Cause<unknown>): boolean { |
| 85 | const error = Option.getOrNull(Cause.findErrorOption(cause)); |
| 86 | if (isUndeclaredStatusError(error)) { |
| 87 | return error.status === 401 || error.status === 403; |
| 88 | } |
| 89 | // A twice-rejected relay credential arrives wrapping the `authenticated: false` response. |
| 90 | if (isAuthFetchError(error)) return isSessionResponse(error.cause); |
| 91 | return isSessionRejectionError(error); |
| 92 | } |
| 93 | |
| 94 | export const fetchEnvironmentSessionState = Effect.fn( |
| 95 | "clientRuntime.state.fetchEnvironmentSessionState", |
| 96 | )(function* (input: { |
| 97 | readonly prepared: PreparedConnection; |
| 98 | readonly signer: Option.Option<ManagedRelay.ManagedRelayDpopSigner["Service"]>; |
| 99 | readonly remoteAuthorization?: Option.Option< |
| 100 | RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"] |
| 101 | >; |
| 102 | readonly timeoutMs?: number; |
| 103 | }) { |
| 104 | const request = ( |
| 105 | timeoutMs: number, |
| 106 | ): Effect.Effect<AuthSessionState, RemoteEnvironmentRequestError, HttpClient.HttpClient> => |
| 107 | executeAuthenticatedEnvironmentHttpRequest({ |
| 108 | ...input, |
| 109 | group: "auth", |
| 110 | method: "GET", |
| 111 | url: (urls) => urls.session(), |
| 112 | timeoutMs, |
| 113 | request: ({ client, headers }) => client.session({ headers }), |
| 114 | // This endpoint returns 200 with authenticated:false for expired credentials. |
| 115 | isUnauthorizedResponse: (response) => !response.authenticated, |
| 116 | }).pipe( |
| 117 | // A timeout says nothing about grants; failing would show a busy host as read-only. |
| 118 | Effect.catchTags({ |
| 119 | RemoteEnvironmentAuthTimeoutError: (error) => { |
| 120 | const nextTimeoutMs = Math.min(timeoutMs * 2, MAX_SESSION_STATE_TIMEOUT_MS); |
| 121 | return nextTimeoutMs > timeoutMs ? request(nextTimeoutMs) : Effect.fail(error); |
| 122 | }, |
| 123 | }), |
| 124 | ); |
| 125 | return yield* request(input.timeoutMs ?? DEFAULT_SESSION_STATE_TIMEOUT_MS); |
| 126 | }); |
| 127 | |
| 128 | function makeEnvironmentSessionAtoms<R, E>( |
| 129 | runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, E>, |
| 130 | ) { |
| 131 | const initialConfigAtom = Atom.family((environmentId: EnvironmentId) => |
| 132 | runtime.atom( |
| 133 | followStreamInEnvironment( |
| 134 | environmentId, |
| 135 | Stream.unwrap( |
| 136 | EnvironmentSupervisor.EnvironmentSupervisor.pipe( |
| 137 | Effect.map((supervisor) => |
| 138 | SubscriptionRef.changes(supervisor.session).pipe( |
| 139 | Stream.mapEffect( |
| 140 | Option.match({ |
| 141 | onNone: () => Effect.succeed(Option.none<ServerConfig>()), |
| 142 | onSome: (session) => initialConfigOption(session.initialConfig), |
| 143 | }), |
| 144 | ), |
| 145 | ), |
| 146 | ), |
| 147 | ), |
| 148 | ), |
| 149 | ), |
| 150 | { initialValue: Option.none() }, |
| 151 | ), |
| 152 | ); |
| 153 | |
| 154 | // This is only the bootstrap config captured when a transport session is |
| 155 | // established. Consumers that need current provider/settings state must use |
| 156 | // createServerEnvironmentAtoms(...).configValueAtom instead. |
| 157 | const initialConfigValueAtom = Atom.family((environmentId: EnvironmentId) => |
| 158 | Atom.make((get): ServerConfig | null => |
| 159 | pipe( |
| 160 | get(initialConfigAtom(environmentId)), |
| 161 | AsyncResult.value, |
| 162 | Option.flatten, |
| 163 | Option.getOrNull, |
| 164 | ), |
| 165 | ).pipe(Atom.withLabel(`environment-config-value:${environmentId}`)), |
| 166 | ); |
| 167 | |
| 168 | const preparedConnectionAtom = Atom.family((environmentId: EnvironmentId) => |
| 169 | runtime.atom( |
| 170 | followStreamInEnvironment( |
| 171 | environmentId, |
| 172 | Stream.unwrap( |
| 173 | EnvironmentSupervisor.EnvironmentSupervisor.pipe( |
| 174 | Effect.map((supervisor) => SubscriptionRef.changes(supervisor.prepared)), |
| 175 | ), |
| 176 | ), |
| 177 | ), |
| 178 | { initialValue: Option.none<PreparedConnection>() }, |
| 179 | ), |
| 180 | ); |
| 181 | |
| 182 | const preparedConnectionValueAtom = Atom.family((environmentId: EnvironmentId) => |
| 183 | Atom.make((get) => |
| 184 | AsyncResult.getOrElse(get(preparedConnectionAtom(environmentId)), () => |
| 185 | Option.none<PreparedConnection>(), |
| 186 | ), |
| 187 | ).pipe(Atom.withLabel(`environment-prepared-connection:${environmentId}`)), |
| 188 | ); |
| 189 | |
| 190 | const transportSessionAtom = Atom.family((environmentId: EnvironmentId) => |
| 191 | runtime.atom( |
| 192 | followStreamInEnvironment( |
| 193 | environmentId, |
| 194 | Stream.unwrap( |
| 195 | EnvironmentSupervisor.EnvironmentSupervisor.pipe( |
| 196 | Effect.map((supervisor) => SubscriptionRef.changes(supervisor.session)), |
| 197 | ), |
| 198 | ), |
| 199 | ), |
| 200 | { initialValue: Option.none() }, |
| 201 | ), |
| 202 | ); |
| 203 | |
| 204 | const sessionStateAtom = Atom.family((environmentId: EnvironmentId) => { |
| 205 | let consecutiveFailures = 0; |
| 206 | let backoffConnection: RpcSession | null = null; |
| 207 | return runtime |
| 208 | .atom((get) => { |
| 209 | const prepared = Option.getOrNull(get(preparedConnectionValueAtom(environmentId))); |
| 210 | // Each established connection fetches anew, and a failure retries while it stays up, |
| 211 | // so a fetch that failed mid-reconnect cannot outlive the socket that recovered. |
| 212 | const connection = AsyncResult.getOrElse(get(transportSessionAtom(environmentId)), () => |
| 213 | Option.none(), |
| 214 | ); |
| 215 | if (prepared === null || Option.isNone(connection)) { |
| 216 | return Effect.never; |
| 217 | } |
| 218 | if (connection.value !== backoffConnection) { |
| 219 | backoffConnection = connection.value; |
| 220 | consecutiveFailures = 0; |
| 221 | } |
| 222 | return Effect.gen(function* () { |
| 223 | const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner); |
| 224 | const remoteAuthorization = yield* Effect.serviceOption( |
| 225 | RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization, |
| 226 | ); |
| 227 | const client = yield* Effect.serviceOption(HttpClient.HttpClient); |
| 228 | if (Option.isNone(client)) return yield* new SessionHttpClientUnavailable(); |
| 229 | return yield* fetchEnvironmentSessionState({ |
| 230 | prepared, |
| 231 | signer, |
| 232 | remoteAuthorization, |
| 233 | }).pipe(Effect.provideService(HttpClient.HttpClient, client.value)); |
| 234 | }).pipe( |
| 235 | Effect.tap(() => |
| 236 | Effect.sync(() => { |
| 237 | consecutiveFailures = 0; |
| 238 | }), |
| 239 | ), |
| 240 | Effect.tapError(() => { |
| 241 | const delayMs = Math.min( |
| 242 | SESSION_STATE_RETRY_BASE_MS * 2 ** consecutiveFailures, |
| 243 | SESSION_STATE_RETRY_MAX_MS, |
| 244 | ); |
| 245 | consecutiveFailures += 1; |
| 246 | return Effect.sleep(delayMs).pipe( |
| 247 | Effect.andThen(Effect.sync(() => get.refreshSelf())), |
| 248 | Effect.forkScoped, |
| 249 | ); |
| 250 | }), |
| 251 | ); |
| 252 | }) |
| 253 | .pipe( |
| 254 | Atom.swr({ staleTime: 30_000, revalidateOnMount: true }), |
| 255 | Atom.setIdleTTL(5 * 60_000), |
| 256 | Atom.withLabel(`environment-session-state:${environmentId}`), |
| 257 | ); |
| 258 | }); |
| 259 | |
| 260 | const sessionStateValueAtom = Atom.family((environmentId: EnvironmentId) => |
| 261 | Atom.make( |
| 262 | (get): AuthSessionState | null => |
| 263 | AsyncResult.getOrElse(get(sessionStateAtom(environmentId)), () => null) ?? null, |
| 264 | ).pipe(Atom.withLabel(`environment-session-state-value:${environmentId}`)), |
| 265 | ); |
| 266 | |
| 267 | return { |
| 268 | initialConfigAtom, |
| 269 | initialConfigValueAtom, |
| 270 | preparedConnectionAtom, |
| 271 | preparedConnectionValueAtom, |
| 272 | sessionStateAtom, |
| 273 | sessionStateValueAtom, |
| 274 | transportSessionAtom, |
| 275 | }; |
| 276 | } |
| 277 | |
| 278 | const sessionAtomsByRuntime = new WeakMap<object, ReturnType<typeof makeEnvironmentSessionAtoms>>(); |
| 279 | |
| 280 | export function createEnvironmentSessionAtoms<R, E>( |
| 281 | runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, E>, |
| 282 | ): ReturnType<typeof makeEnvironmentSessionAtoms<R, E>> { |
| 283 | const existing = sessionAtomsByRuntime.get(runtime); |
| 284 | if (existing) return existing as ReturnType<typeof makeEnvironmentSessionAtoms<R, E>>; |
| 285 | const atoms = makeEnvironmentSessionAtoms(runtime); |
| 286 | sessionAtomsByRuntime.set(runtime, atoms); |
| 287 | return atoms; |
| 288 | } |