The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Config from "effect/Config"; |
| 2 | import * as ConfigProvider from "effect/ConfigProvider"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as Option from "effect/Option"; |
| 5 | import * as Schema from "effect/Schema"; |
| 6 | import { UserFacingError } from "../UserFacingError.ts"; |
| 7 | import { loadConfigProvider } from "../Util/ConfigProvider.ts"; |
| 8 | import { AuthError, getAuthProvider, presentEnvironment } from "./AuthProvider.ts"; |
| 9 | import { cacheUntilExpiry } from "./CredentialsCache.ts"; |
| 10 | import { ProfileStore, reloadProviderConfig, SuppressMissingProviderConfig } from "./Profile.ts"; |
| 11 | |
| 12 | /** |
| 13 | * Resolve the selected Alchemy profile after the command's dotenv provider is |
| 14 | * known. An omitted explicit override remains absent so it does not shadow |
| 15 | * `ALCHEMY_PROFILE` from `.env` / `--env-file`. |
| 16 | */ |
| 17 | export const resolveProfileSelection = Effect.fn(function* ( |
| 18 | envFile: Option.Option<string>, |
| 19 | override: string | undefined, |
| 20 | ) { |
| 21 | const base = yield* loadConfigProvider(envFile); |
| 22 | const profiles = yield* ProfileStore; |
| 23 | const selected = yield* profiles.current.pipe( |
| 24 | Effect.provideService(ConfigProvider.ConfigProvider, withProfileOverride(base, override)), |
| 25 | ); |
| 26 | return { |
| 27 | ...selected, |
| 28 | source: override === undefined ? selected.source : ("command-line" as const), |
| 29 | }; |
| 30 | }); |
| 31 | |
| 32 | export const resolveProfileName = Effect.fn(function* ( |
| 33 | envFile: Option.Option<string>, |
| 34 | override: string | undefined, |
| 35 | ) { |
| 36 | return (yield* resolveProfileSelection(envFile, override)).name; |
| 37 | }); |
| 38 | |
| 39 | /** |
| 40 | * The shared preamble of every per-cloud `fromAuthProvider` / |
| 41 | * `fromEnvironment` layer. Precedence: environment credentials (process |
| 42 | * environment plus `.env` / `--env-file`) whenever the provider's declared |
| 43 | * contract is fully present — CI or not, selected profile or not — then, in |
| 44 | * CI, the provider's environment resolution alone (profiles do not exist |
| 45 | * there), otherwise the selected profile. |
| 46 | */ |
| 47 | export const resolveProviderConfig = <C extends { method: string } = any, Credentials = any>( |
| 48 | providerName: string, |
| 49 | ) => |
| 50 | Effect.gen(function* () { |
| 51 | const auth = yield* getAuthProvider<C, Credentials>(providerName); |
| 52 | if (auth.readEnvironment !== undefined) { |
| 53 | const used = yield* presentEnvironment(auth.environment); |
| 54 | if (used !== undefined) { |
| 55 | if (!(yield* SuppressMissingProviderConfig)) { |
| 56 | yield* auth.logEnvironmentCredentials(used); |
| 57 | } |
| 58 | return { |
| 59 | auth, |
| 60 | profileName: undefined, |
| 61 | config: undefined, |
| 62 | resolve: auth.readEnvironment, |
| 63 | source: "environment" as const, |
| 64 | }; |
| 65 | } |
| 66 | } |
| 67 | const ci = yield* Config.Boolean("CI").pipe(Config.withDefault(false)); |
| 68 | if (ci) { |
| 69 | if (auth.readEnvironment === undefined) { |
| 70 | return yield* AuthError.make({ |
| 71 | message: `Auth provider '${providerName}' does not support environment credentials in CI.`, |
| 72 | }); |
| 73 | } |
| 74 | return { |
| 75 | auth, |
| 76 | profileName: undefined, |
| 77 | config: undefined, |
| 78 | resolve: auth.readEnvironment, |
| 79 | source: "environment" as const, |
| 80 | }; |
| 81 | } |
| 82 | const profile = yield* ProfileStore; |
| 83 | const selection = yield* profile.current; |
| 84 | const profileName = selection.name; |
| 85 | const config = yield* profile.loadProviderConfig(auth, profileName); |
| 86 | return { |
| 87 | auth, |
| 88 | profileName, |
| 89 | config, |
| 90 | // Reload under the credentials lock on every resolve: a refresh |
| 91 | // rotates the stored token, so `config` goes stale after the first one. |
| 92 | resolve: auth.read(profileName, reloadProviderConfig(profile, auth, profileName), (updated) => |
| 93 | profile.setProviderConfig(profileName, providerName, updated).pipe( |
| 94 | Effect.mapError((cause) => |
| 95 | AuthError.make({ |
| 96 | message: `${providerName}: could not persist refreshed credentials for profile '${profileName}'.`, |
| 97 | cause, |
| 98 | }), |
| 99 | ), |
| 100 | ), |
| 101 | ), |
| 102 | source: "profile" as const, |
| 103 | }; |
| 104 | }); |
| 105 | |
| 106 | /** |
| 107 | * Defer an effect that a layer hands out as its service value. The effect |
| 108 | * runs on first use, outside the layer build, so the services it needs are |
| 109 | * captured now and provided to it. Building the layer then never runs the |
| 110 | * effect, e.g. never requires a configured profile. |
| 111 | * |
| 112 | * The `ConfigProvider` is a reference, so it is not part of `R`; capture it |
| 113 | * too. Otherwise the first use reads config through whatever provider is |
| 114 | * ambient there — e.g. a Function's init, which binds every key it loads into |
| 115 | * the Function's env and would ship the deployer's credentials (#1842). |
| 116 | */ |
| 117 | export const deferUntilFirstUse = <A, E, R>(resolve: Effect.Effect<A, E, R>) => |
| 118 | Effect.map( |
| 119 | Effect.all([Effect.context<R>(), ConfigProvider.ConfigProvider]), |
| 120 | ([context, configProvider]) => |
| 121 | resolve.pipe( |
| 122 | Effect.provideService(ConfigProvider.ConfigProvider, configProvider), |
| 123 | Effect.provideContext(context), |
| 124 | ), |
| 125 | ); |
| 126 | |
| 127 | /** |
| 128 | * A provider's credentials could not be resolved when a cloud operation first |
| 129 | * needed them: no profile, the provider is not configured in it, or the |
| 130 | * stored credentials can no longer be read or refreshed. |
| 131 | */ |
| 132 | export class CredentialsUnavailable extends Schema.TaggedError<CredentialsUnavailable>()( |
| 133 | "CredentialsUnavailable", |
| 134 | { |
| 135 | provider: Schema.String, |
| 136 | message: Schema.String, |
| 137 | cause: Schema.optional(Schema.Defect()), |
| 138 | }, |
| 139 | ) { |
| 140 | readonly [UserFacingError] = true; |
| 141 | } |
| 142 | |
| 143 | /** |
| 144 | * Credential services are `Effect<Config>` with no error channel, so a |
| 145 | * failed resolution can only leave them as a defect. Die with |
| 146 | * {@link CredentialsUnavailable} so the engine can tell it apart from a |
| 147 | * provider crash and fail the operation with `CredentialsRequired`. |
| 148 | */ |
| 149 | export const orDieCredentialsUnavailable = |
| 150 | (provider: string) => |
| 151 | <A, E extends { readonly message: string }, R>(self: Effect.Effect<A, E, R>) => |
| 152 | self.pipe( |
| 153 | Effect.mapError((cause) => |
| 154 | CredentialsUnavailable.make({ |
| 155 | provider, |
| 156 | message: cause.message, |
| 157 | cause, |
| 158 | }), |
| 159 | ), |
| 160 | Effect.orDie, |
| 161 | ); |
| 162 | |
| 163 | /** |
| 164 | * The credential recipe behind every provider's `fromAuthProvider` layer: |
| 165 | * {@link resolveProviderConfig}'s precedence, deferred until first use (so |
| 166 | * building provider layers never needs a configured profile), cached until |
| 167 | * shortly before the credentials expire (forever when `expiresAt` is omitted |
| 168 | * or returns `undefined`; failures are never cached, so a later `alchemy |
| 169 | * profile` login is picked up), and mapped onto the client's shape. |
| 170 | * |
| 171 | * A failed resolution fails with {@link CredentialsUnavailable}, which the |
| 172 | * engine reports as `CredentialsRequired`. `E` types that failure into the |
| 173 | * client SDK's own credentials channel (e.g. distilled's `ConfigError`), so |
| 174 | * users never see a new error type. |
| 175 | * |
| 176 | * ```ts |
| 177 | * export const fromAuthProvider = () => |
| 178 | * Layer.effect( |
| 179 | * Credentials, |
| 180 | * lazyCredentials<StripeResolvedCredentials, ConfigError>()( |
| 181 | * STRIPE_AUTH_PROVIDER_NAME, |
| 182 | * (creds) => ({ apiKey: creds.apiKey, apiBaseUrl: creds.apiBaseUrl }), |
| 183 | * ), |
| 184 | * ); |
| 185 | * ``` |
| 186 | */ |
| 187 | export const lazyCredentials = <Resolved, E = CredentialsUnavailable>() => |
| 188 | Effect.fn("lazyCredentials")(function* <A>( |
| 189 | providerName: string, |
| 190 | toClient: (resolved: Resolved) => A, |
| 191 | options?: { readonly expiresAt?: (resolved: Resolved) => number | undefined }, |
| 192 | ) { |
| 193 | const unavailable = (prefix: string) => (cause: { readonly message: string }) => |
| 194 | CredentialsUnavailable.make({ |
| 195 | provider: providerName, |
| 196 | message: `${prefix}${cause.message}`, |
| 197 | cause, |
| 198 | }); |
| 199 | const resolve = yield* resolveProviderConfig<{ method: string }, Resolved>(providerName).pipe( |
| 200 | Effect.mapError(unavailable("")), |
| 201 | Effect.flatMap(({ profileName, resolve }) => { |
| 202 | const from = profileName === undefined ? "the environment" : `profile '${profileName}'`; |
| 203 | return Effect.logDebug(`${providerName}: credentials from ${from}`).pipe( |
| 204 | Effect.annotateLogs({ provider: providerName }), |
| 205 | Effect.andThen(resolve), |
| 206 | Effect.mapError( |
| 207 | unavailable(`Failed to resolve ${providerName} credentials from ${from}: `), |
| 208 | ), |
| 209 | ); |
| 210 | }), |
| 211 | deferUntilFirstUse, |
| 212 | ); |
| 213 | const cached = yield* cacheUntilExpiry(resolve, options?.expiresAt ?? (() => undefined)); |
| 214 | // SAFETY: E is only the SDK channel the CredentialsUnavailable fails |
| 215 | // through; the engine matches its tag around every provider call. |
| 216 | // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- see SAFETY above |
| 217 | return cached.pipe(Effect.map(toClient)) as Effect.Effect<A, E>; |
| 218 | }); |
| 219 | |
| 220 | /** Let an explicit profile override configured selection without disturbing other keys. */ |
| 221 | export const withProfileOverride = ( |
| 222 | base: ConfigProvider.ConfigProvider, |
| 223 | profile: string | undefined, |
| 224 | ): ConfigProvider.ConfigProvider => { |
| 225 | if (profile === undefined) return base; |
| 226 | const overrides: Record<string, string> = { ALCHEMY_PROFILE: profile }; |
| 227 | const overrideProvider = ConfigProvider.make((path) => |
| 228 | Effect.succeed( |
| 229 | path.length === 1 && typeof path[0] === "string" && path[0] in overrides |
| 230 | ? ConfigProvider.makeValue(overrides[path[0]]!) |
| 231 | : undefined, |
| 232 | ), |
| 233 | ); |
| 234 | return ConfigProvider.orElse(base)(overrideProvider); |
| 235 | }; |