The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | type ServerProviderAuth, |
| 3 | type ServerProviderModel, |
| 4 | type ServerProviderSubProvider, |
| 5 | } from "@t3tools/contracts"; |
| 6 | import type { FxSettings } from "../settings.ts"; |
| 7 | import { createModelCapabilities } from "@t3tools/shared/model"; |
| 8 | import { resolveSpawnCommand } from "@t3tools/shared/shell"; |
| 9 | import * as DateTime from "effect/DateTime"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as FileSystem from "effect/FileSystem"; |
| 12 | import * as Option from "effect/Option"; |
| 13 | import * as Path from "effect/Path"; |
| 14 | import * as Result from "effect/Result"; |
| 15 | import * as Schema from "effect/Schema"; |
| 16 | import * as ChildProcess from "effect/process/ChildProcess"; |
| 17 | import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 18 | |
| 19 | import { |
| 20 | FX_DEFAULT_MODEL_SLUG, |
| 21 | FX_DRIVER_KIND, |
| 22 | FX_EFFORT_OPTION_DESCRIPTOR, |
| 23 | FX_FULL_ACCESS_MODE_ID, |
| 24 | FX_SUPPORTED_RUNTIME_MODES, |
| 25 | type FxModelChoice, |
| 26 | fxModelSlug, |
| 27 | } from "./acpSupport.ts"; |
| 28 | import { |
| 29 | AUTH_PROBE_TIMEOUT_MS, |
| 30 | buildServerProvider, |
| 31 | isCommandMissingCause, |
| 32 | nonEmptyTrimmed, |
| 33 | parseCliVersionResult, |
| 34 | type ProviderProbeResult, |
| 35 | providerModelsFromSettings, |
| 36 | type ServerProviderDraft, |
| 37 | providerProbeEnvironment, |
| 38 | resolveProviderProbeTimeoutMs, |
| 39 | spawnAndCollect, |
| 40 | } from "@t3tools/provider-core/server/snapshotProbe"; |
| 41 | |
| 42 | const fxPresentation = (fullAccess: boolean) => ({ |
| 43 | displayName: "fx", |
| 44 | showInteractionModeToggle: false, |
| 45 | supportedRuntimeModes: fullAccess |
| 46 | ? [...FX_SUPPORTED_RUNTIME_MODES, "full-access" as const] |
| 47 | : FX_SUPPORTED_RUNTIME_MODES, |
| 48 | }); |
| 49 | const FX_MODEL_CAPABILITIES = createModelCapabilities({ |
| 50 | optionDescriptors: [FX_EFFORT_OPTION_DESCRIPTOR], |
| 51 | }); |
| 52 | |
| 53 | /** fx's built-in backends, in the order its `provider` option lists them. */ |
| 54 | const FX_BUILT_IN_BACKENDS = [ |
| 55 | { id: "gateway", name: "Vercel AI Gateway", login: "fx login" }, |
| 56 | { id: "codex", name: "Codex subscription", login: "fx login codex" }, |
| 57 | { id: "grok", name: "Grok subscription", login: "fx login grok" }, |
| 58 | ] as const; |
| 59 | |
| 60 | /** What `fx status` and `fx models` report for one backend. */ |
| 61 | interface FxBackendProbe { |
| 62 | readonly id: string; |
| 63 | readonly name: string; |
| 64 | /** Undefined when its status could not be read. */ |
| 65 | readonly signedIn: boolean | undefined; |
| 66 | readonly signInHint: string; |
| 67 | readonly models: ReadonlyArray<string> | undefined; |
| 68 | } |
| 69 | |
| 70 | /** |
| 71 | * "Default" runs what fx would start a new session on in the thread's |
| 72 | * folder; the label shows the machine-wide choice. Other models carry their |
| 73 | * backend in the slug, and only signed-in backends list any. |
| 74 | */ |
| 75 | const fxModels = ( |
| 76 | settings: FxSettings, |
| 77 | defaultModel?: string, |
| 78 | backends: ReadonlyArray<FxBackendProbe> = [], |
| 79 | ): ReadonlyArray<ServerProviderModel> => |
| 80 | providerModelsFromSettings( |
| 81 | [ |
| 82 | { |
| 83 | slug: FX_DEFAULT_MODEL_SLUG, |
| 84 | name: defaultModel === undefined ? "Default" : `Default (${defaultModel})`, |
| 85 | isCustom: false, |
| 86 | isDefault: true, |
| 87 | capabilities: FX_MODEL_CAPABILITIES, |
| 88 | }, |
| 89 | ...backends.flatMap((backend) => |
| 90 | backend.signedIn === false |
| 91 | ? [] |
| 92 | : [...new Set(backend.models)].map((id) => ({ |
| 93 | slug: fxModelSlug(backend.id, id), |
| 94 | name: id, |
| 95 | subProvider: backend.name, |
| 96 | isCustom: false, |
| 97 | capabilities: FX_MODEL_CAPABILITIES, |
| 98 | })), |
| 99 | ), |
| 100 | ], |
| 101 | settings.customModels, |
| 102 | FX_MODEL_CAPABILITIES, |
| 103 | ); |
| 104 | |
| 105 | const fxSubProviders = ( |
| 106 | backends: ReadonlyArray<FxBackendProbe>, |
| 107 | ): ReadonlyArray<ServerProviderSubProvider> => |
| 108 | // A failed listing does not stop a backend's models from running; the server keeps its earlier ones. |
| 109 | backends.map((backend) => |
| 110 | backend.signedIn === false |
| 111 | ? { name: backend.name, unavailableReason: backend.signInHint } |
| 112 | : { name: backend.name }, |
| 113 | ); |
| 114 | |
| 115 | const snapshot = ( |
| 116 | settings: FxSettings, |
| 117 | checkedAt: string, |
| 118 | probe: ProviderProbeResult, |
| 119 | defaultModel?: string, |
| 120 | backends: ReadonlyArray<FxBackendProbe> = [], |
| 121 | fullAccess = false, |
| 122 | ): ServerProviderDraft => ({ |
| 123 | ...buildServerProvider({ |
| 124 | driver: FX_DRIVER_KIND, |
| 125 | presentation: fxPresentation(fullAccess), |
| 126 | enabled: settings.enabled, |
| 127 | checkedAt, |
| 128 | models: fxModels(settings, defaultModel, backends), |
| 129 | probe, |
| 130 | }), |
| 131 | ...(backends.length > 0 ? { subProviders: fxSubProviders(backends) } : {}), |
| 132 | // Every `fx acp` session is saved under `~/.fx` and ACP has no session |
| 133 | // delete, so a throwaway text-generation session would stay on disk. |
| 134 | supportsTextGeneration: false, |
| 135 | }); |
| 136 | |
| 137 | export const buildInitialFxProviderSnapshot = ( |
| 138 | settings: FxSettings, |
| 139 | ): Effect.Effect<ServerProviderDraft> => |
| 140 | Effect.map(DateTime.now, (now) => |
| 141 | snapshot(settings, DateTime.formatIso(now), { |
| 142 | installed: settings.enabled, |
| 143 | version: null, |
| 144 | status: "warning", |
| 145 | auth: { status: "unknown" }, |
| 146 | message: settings.enabled |
| 147 | ? "Checking fx CLI availability..." |
| 148 | : "fx is disabled in T3 Code settings.", |
| 149 | }), |
| 150 | ); |
| 151 | |
| 152 | const runFxCli = Effect.fn("runFxCli")(function* ( |
| 153 | settings: FxSettings, |
| 154 | args: ReadonlyArray<string>, |
| 155 | environment: NodeJS.ProcessEnv, |
| 156 | cwd?: string, |
| 157 | ) { |
| 158 | const command = settings.binaryPath || "fx"; |
| 159 | const spawnCommand = yield* resolveSpawnCommand(command, args, { env: environment }); |
| 160 | return yield* spawnAndCollect( |
| 161 | command, |
| 162 | ChildProcess.make(spawnCommand.command, spawnCommand.args, { |
| 163 | env: environment, |
| 164 | shell: spawnCommand.shell, |
| 165 | ...(cwd === undefined ? {} : { cwd }), |
| 166 | }), |
| 167 | ); |
| 168 | }); |
| 169 | |
| 170 | /** Stdout of a successful run, or none. Never opens an ACP session, which fx would save. */ |
| 171 | const readFxCli = ( |
| 172 | settings: FxSettings, |
| 173 | args: ReadonlyArray<string>, |
| 174 | environment: NodeJS.ProcessEnv, |
| 175 | cwd?: string, |
| 176 | ) => |
| 177 | runFxCli(settings, args, environment, cwd).pipe( |
| 178 | Effect.timeoutOption(resolveProviderProbeTimeoutMs("fx", AUTH_PROBE_TIMEOUT_MS, environment)), |
| 179 | Effect.map(Option.filter((output) => output.code === 0)), |
| 180 | Effect.map(Option.map((output) => output.stdout)), |
| 181 | Effect.orElseSucceed(() => Option.none<string>()), |
| 182 | ); |
| 183 | |
| 184 | /** |
| 185 | * `fx status --json`: `auth` names the login method, `missing` when signed |
| 186 | * out. `model_source` names a backend other than the gateway, by its label |
| 187 | * for a built-in one and its id for a configured endpoint. fx 0.0.14+ also |
| 188 | * lists the ACP session `modes`; 0.0.13 omits them. |
| 189 | */ |
| 190 | const FxStatus = Schema.fromJsonString( |
| 191 | Schema.Struct({ |
| 192 | auth: Schema.optional(Schema.String), |
| 193 | auth_help: Schema.optional(Schema.String), |
| 194 | model: Schema.optional(Schema.String), |
| 195 | model_source: Schema.optional(Schema.String), |
| 196 | modes: Schema.optional(Schema.Array(Schema.Struct({ id: Schema.String }))), |
| 197 | }), |
| 198 | ); |
| 199 | const decodeFxStatus = Schema.decodeUnknownOption(FxStatus); |
| 200 | const FxModels = Schema.fromJsonString(Schema.Struct({ ids: Schema.Array(Schema.String) })); |
| 201 | const decodeFxModels = Schema.decodeUnknownOption(FxModels); |
| 202 | const FxProfileSettings = Schema.fromJsonString( |
| 203 | Schema.Struct({ |
| 204 | providers: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), |
| 205 | }), |
| 206 | ); |
| 207 | const decodeFxProfileSettings = Schema.decodeUnknownOption(FxProfileSettings); |
| 208 | |
| 209 | const VERSION_PROBE_TIMEOUT_MS = 10_000; |
| 210 | |
| 211 | function fxAuth(auth: string | undefined): ServerProviderAuth { |
| 212 | const method = nonEmptyTrimmed(auth); |
| 213 | if (method === undefined) return { status: "unknown" }; |
| 214 | return method === "missing" |
| 215 | ? { status: "unauthenticated" } |
| 216 | : { status: "authenticated", label: method }; |
| 217 | } |
| 218 | |
| 219 | const fxStatusBackend = (modelSource: string | undefined) => { |
| 220 | const source = nonEmptyTrimmed(modelSource); |
| 221 | if (source === undefined) return "gateway"; |
| 222 | return FX_BUILT_IN_BACKENDS.find((backend) => backend.name === source)?.id ?? source; |
| 223 | }; |
| 224 | |
| 225 | /** Configured endpoints are the `providers` keys of fx's profile settings. */ |
| 226 | const readFxConfiguredBackends = Effect.fn("readFxConfiguredBackends")(function* ( |
| 227 | environment: NodeJS.ProcessEnv, |
| 228 | ) { |
| 229 | const path = yield* Path.Path; |
| 230 | // fx keeps its profile in `FX_HOME` when set, else `~/.fx`. |
| 231 | const fxHome = environment.FX_HOME?.trim(); |
| 232 | const home = environment.HOME?.trim(); |
| 233 | const profile = fxHome ? fxHome : home ? path.join(home, ".fx") : undefined; |
| 234 | if (profile === undefined) return []; |
| 235 | const fileSystem = yield* FileSystem.FileSystem; |
| 236 | const text = yield* fileSystem |
| 237 | .readFileString(path.join(profile, "settings.json")) |
| 238 | .pipe(Effect.orElseSucceed(() => "")); |
| 239 | const providers = Option.getOrUndefined(decodeFxProfileSettings(text))?.providers ?? {}; |
| 240 | // fx's own id rule; the built-in names are reserved. |
| 241 | return Object.keys(providers).filter( |
| 242 | (id) => |
| 243 | /^[A-Za-z][\w-]*$/.test(id) && |
| 244 | !FX_BUILT_IN_BACKENDS.some((backend) => backend.id === id.toLowerCase()), |
| 245 | ); |
| 246 | }); |
| 247 | |
| 248 | /** |
| 249 | * `FX_PROVIDER` points `fx status` and `fx models` at one backend. fx |
| 250 | * refuses a backend without a saved model unless `FX_MODEL` names one; any |
| 251 | * value does, since neither command uses it. |
| 252 | */ |
| 253 | const probeFxBackend = Effect.fn("probeFxBackend")(function* ( |
| 254 | settings: FxSettings, |
| 255 | environment: NodeJS.ProcessEnv, |
| 256 | backend: { readonly id: string; readonly name: string; readonly login?: string }, |
| 257 | ) { |
| 258 | const env = { ...environment, FX_PROVIDER: backend.id, FX_MODEL: FX_DEFAULT_MODEL_SLUG }; |
| 259 | const status = Option.getOrUndefined( |
| 260 | Option.flatMap(yield* readFxCli(settings, ["status", "--json"], env), decodeFxStatus), |
| 261 | ); |
| 262 | const auth = fxAuth(status?.auth).status; |
| 263 | const signedIn = auth === "unknown" ? undefined : auth === "authenticated"; |
| 264 | const models = |
| 265 | signedIn === false |
| 266 | ? undefined |
| 267 | : Option.getOrUndefined( |
| 268 | Option.flatMap(yield* readFxCli(settings, ["models", "--json"], env), decodeFxModels), |
| 269 | )?.ids.flatMap((id) => nonEmptyTrimmed(id) ?? []); |
| 270 | return { |
| 271 | id: backend.id, |
| 272 | name: backend.name, |
| 273 | signedIn, |
| 274 | signInHint: |
| 275 | backend.login === undefined |
| 276 | ? (nonEmptyTrimmed(status?.auth_help) ?? "fx has no credential for this backend.") |
| 277 | : `Signed out. Run \`${backend.login}\` on this machine.`, |
| 278 | models, |
| 279 | } satisfies FxBackendProbe; |
| 280 | }); |
| 281 | |
| 282 | /** |
| 283 | * Reads `fx --version`, `fx status --json` (the default backend and model) |
| 284 | * and, for every backend, its sign-in and `fx models --json`. |
| 285 | */ |
| 286 | export const checkFxProviderStatus = Effect.fn("checkFxProviderStatus")(function* ( |
| 287 | settings: FxSettings, |
| 288 | environment: NodeJS.ProcessEnv, |
| 289 | ): Effect.fn.Return< |
| 290 | ServerProviderDraft, |
| 291 | never, |
| 292 | ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path |
| 293 | > { |
| 294 | const checkedAt = DateTime.formatIso(yield* DateTime.now); |
| 295 | if (!settings.enabled) { |
| 296 | return snapshot(settings, checkedAt, { |
| 297 | installed: false, |
| 298 | version: null, |
| 299 | status: "warning", |
| 300 | auth: { status: "unknown" }, |
| 301 | message: "fx is disabled in T3 Code settings.", |
| 302 | }); |
| 303 | } |
| 304 | |
| 305 | const probeEnvironment = providerProbeEnvironment(environment); |
| 306 | const versionResult = yield* runFxCli(settings, ["--version"], probeEnvironment).pipe( |
| 307 | Effect.timeoutOption( |
| 308 | resolveProviderProbeTimeoutMs("fx", VERSION_PROBE_TIMEOUT_MS, environment), |
| 309 | ), |
| 310 | Effect.result, |
| 311 | ); |
| 312 | if (Result.isFailure(versionResult) || Option.isNone(versionResult.success)) { |
| 313 | const missing = Result.isFailure(versionResult) && isCommandMissingCause(versionResult.failure); |
| 314 | return snapshot(settings, checkedAt, { |
| 315 | installed: !missing, |
| 316 | version: null, |
| 317 | status: "error", |
| 318 | auth: { status: "unknown" }, |
| 319 | message: missing ? "fx is not installed or not on PATH." : "Failed to run `fx --version`.", |
| 320 | }); |
| 321 | } |
| 322 | const versionOutput = versionResult.success.value; |
| 323 | const version = parseCliVersionResult(versionOutput); |
| 324 | if (versionOutput.code !== 0) { |
| 325 | return snapshot(settings, checkedAt, { |
| 326 | installed: true, |
| 327 | version, |
| 328 | status: "error", |
| 329 | auth: { status: "unknown" }, |
| 330 | message: "fx is installed but failed to run.", |
| 331 | }); |
| 332 | } |
| 333 | |
| 334 | const status = Option.getOrUndefined( |
| 335 | Option.flatMap( |
| 336 | yield* readFxCli(settings, ["status", "--json"], probeEnvironment), |
| 337 | decodeFxStatus, |
| 338 | ), |
| 339 | ); |
| 340 | const backends = yield* Effect.forEach( |
| 341 | [ |
| 342 | ...FX_BUILT_IN_BACKENDS, |
| 343 | ...(yield* readFxConfiguredBackends(environment)).map((id) => ({ id, name: id })), |
| 344 | ], |
| 345 | (backend) => probeFxBackend(settings, probeEnvironment, backend), |
| 346 | { concurrency: "unbounded" }, |
| 347 | ); |
| 348 | const defaultModel = nonEmptyTrimmed(status?.model); |
| 349 | const defaultBackend = backends.find( |
| 350 | (backend) => backend.id === fxStatusBackend(status?.model_source), |
| 351 | ); |
| 352 | // A ready snapshot replaces the model list, so every backend that may be signed in must have listed. |
| 353 | const listed = backends.filter((backend) => backend.signedIn !== false); |
| 354 | const listingFailed = |
| 355 | listed.length === 0 || listed.some((backend) => backend.models === undefined); |
| 356 | const signedIn = backends.find((backend) => backend.signedIn === true); |
| 357 | const statusAuth = fxAuth(status?.auth); |
| 358 | const auth: ServerProviderAuth = |
| 359 | statusAuth.status !== "authenticated" && signedIn !== undefined |
| 360 | ? { status: "authenticated", label: signedIn.name } |
| 361 | : statusAuth; |
| 362 | const probe = |
| 363 | auth.status === "unauthenticated" |
| 364 | ? { status: "error" as const, message: "Run `fx login` to sign in." } |
| 365 | : auth.status === "unknown" |
| 366 | ? { |
| 367 | status: "warning" as const, |
| 368 | message: "fx is installed but login state could not be determined.", |
| 369 | } |
| 370 | : defaultBackend?.signedIn === false |
| 371 | ? { |
| 372 | status: "warning" as const, |
| 373 | message: `fx's default backend, ${defaultBackend.name}, is signed out. Pick a model on another backend or sign in.`, |
| 374 | } |
| 375 | : listingFailed |
| 376 | ? { |
| 377 | status: "warning" as const, |
| 378 | message: |
| 379 | "fx is installed but model listing failed. Model options may be incomplete.", |
| 380 | } |
| 381 | : { status: "ready" as const }; |
| 382 | return snapshot( |
| 383 | settings, |
| 384 | checkedAt, |
| 385 | { installed: true, version, auth, ...probe }, |
| 386 | defaultModel, |
| 387 | backends, |
| 388 | status?.modes?.some((mode) => mode.id === FX_FULL_ACCESS_MODE_ID) ?? false, |
| 389 | ); |
| 390 | }); |
| 391 | |
| 392 | /** |
| 393 | * The backend and model fx starts a new session on in `cwd`, which can come |
| 394 | * from fx's settings for that folder. Undefined when `fx status` fails. |
| 395 | */ |
| 396 | export const readFxDefaultChoice = Effect.fn("readFxDefaultChoice")(function* ( |
| 397 | settings: FxSettings, |
| 398 | environment: NodeJS.ProcessEnv, |
| 399 | cwd: string, |
| 400 | ): Effect.fn.Return<FxModelChoice | undefined, never, ChildProcessSpawner.ChildProcessSpawner> { |
| 401 | const status = Option.getOrUndefined( |
| 402 | Option.flatMap( |
| 403 | yield* readFxCli(settings, ["status", "--json"], environment, cwd), |
| 404 | decodeFxStatus, |
| 405 | ), |
| 406 | ); |
| 407 | const model = nonEmptyTrimmed(status?.model); |
| 408 | return model === undefined |
| 409 | ? undefined |
| 410 | : { backend: fxStatusBackend(status?.model_source), model }; |
| 411 | }); |