Open History to see the last commit
1import { resolveProviderProbeTimeoutMs } from "@t3tools/provider-core/server/snapshotProbe";
2import { type ServerProviderAuth, type ServerProviderModel } from "@t3tools/contracts";
3import type { FxSettings } from "../settings.ts";
4import { createModelCapabilities } from "@t3tools/shared/model";
5import { resolveSpawnCommand } from "@t3tools/shared/shell";
6import * as DateTime from "effect/DateTime";
7import * as Effect from "effect/Effect";
8import * as Option from "effect/Option";
9import * as Result from "effect/Result";
10import * as Schema from "effect/Schema";
11import * as ChildProcess from "effect/process/ChildProcess";
12import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13
14import {
15 FX_DEFAULT_MODEL_SLUG,
16 FX_DRIVER_KIND,
17 FX_EFFORT_OPTION_DESCRIPTOR,
18 FX_SUPPORTED_RUNTIME_MODES,
19} from "./acpSupport.ts";
20import {
21 AUTH_PROBE_TIMEOUT_MS,
22 buildServerProvider,
23 isCommandMissingCause,
24 nonEmptyTrimmed,
25 parseCliVersionResult,
26 type ProviderProbeResult,
27 providerModelsFromSettings,
28 type ServerProviderDraft,
29 providerProbeEnvironment,
30 spawnAndCollect,
31} from "@t3tools/provider-core/server/snapshotProbe";
32
33const FX_PRESENTATION = {
34 displayName: "fx",
35 showInteractionModeToggle: false,
36 supportedRuntimeModes: FX_SUPPORTED_RUNTIME_MODES,
37} as const;
38const FX_MODEL_CAPABILITIES = createModelCapabilities({
39 optionDescriptors: [FX_EFFORT_OPTION_DESCRIPTOR],
40});
41
42/**
43 * "Default" keeps the model `fx status` reports as its alias, which the
44 * adapter selects for it. `fx models` lists the rest.
45 */
46const fxModels = (
47 settings: FxSettings,
48 defaultModel?: string,
49 listed: ReadonlyArray<string> = [],
50): ReadonlyArray<ServerProviderModel> =>
51 providerModelsFromSettings(
52 [
53 {
54 slug: FX_DEFAULT_MODEL_SLUG,
55 name: defaultModel === undefined ? "Default" : `Default (${defaultModel})`,
56 ...(defaultModel === undefined ? {} : { aliases: [defaultModel] }),
57 isCustom: false,
58 isDefault: true,
59 capabilities: FX_MODEL_CAPABILITIES,
60 },
61 ...listed
62 .filter((id, index) => id !== FX_DEFAULT_MODEL_SLUG && listed.indexOf(id) === index)
63 .map((id) => ({
64 slug: id,
65 name: id,
66 isCustom: false,
67 capabilities: FX_MODEL_CAPABILITIES,
68 })),
69 ],
70 settings.customModels,
71 FX_MODEL_CAPABILITIES,
72 );
73
74const snapshot = (
75 settings: FxSettings,
76 checkedAt: string,
77 probe: ProviderProbeResult,
78 defaultModel?: string,
79 listed?: ReadonlyArray<string>,
80): ServerProviderDraft => ({
81 ...buildServerProvider({
82 // Gives the snapshot its version advisory; fx runs no enrichment pass.
83 driver: FX_DRIVER_KIND,
84 presentation: FX_PRESENTATION,
85 enabled: settings.enabled,
86 checkedAt,
87 models: fxModels(settings, defaultModel, listed),
88 probe,
89 }),
90 // Every `fx acp` session is saved under `~/.fx` and ACP has no session
91 // delete, so a throwaway text-generation session would stay on disk.
92 supportsTextGeneration: false,
93});
94
95export const buildInitialFxProviderSnapshot = (
96 settings: FxSettings,
97): Effect.Effect<ServerProviderDraft> =>
98 Effect.map(DateTime.now, (now) =>
99 snapshot(settings, DateTime.formatIso(now), {
100 installed: settings.enabled,
101 version: null,
102 status: "warning",
103 auth: { status: "unknown" },
104 message: settings.enabled
105 ? "Checking fx CLI availability..."
106 : "fx is disabled in T3 Code settings.",
107 }),
108 );
109
110const runFxCli = Effect.fn("runFxCli")(function* (
111 settings: FxSettings,
112 args: ReadonlyArray<string>,
113 environment: NodeJS.ProcessEnv,
114) {
115 const command = settings.binaryPath || "fx";
116 const spawnCommand = yield* resolveSpawnCommand(command, args, { env: environment });
117 return yield* spawnAndCollect(
118 command,
119 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
120 env: environment,
121 shell: spawnCommand.shell,
122 }),
123 );
124});
125
126/** `fx status --json` on fx 0.0.13: `auth` names the login method, `missing` when signed out. */
127const FxStatus = Schema.fromJsonString(
128 Schema.Struct({
129 auth: Schema.optional(Schema.String),
130 model: Schema.optional(Schema.String),
131 }),
132);
133const decodeFxStatus = Schema.decodeUnknownOption(FxStatus);
134const FxModels = Schema.fromJsonString(Schema.Struct({ ids: Schema.Array(Schema.String) }));
135const decodeFxModels = Schema.decodeUnknownOption(FxModels);
136
137const VERSION_PROBE_TIMEOUT_MS = 10_000;
138
139function fxAuth(auth: string | undefined): ServerProviderAuth {
140 const method = nonEmptyTrimmed(auth);
141 if (method === undefined) return { status: "unknown" };
142 return method === "missing"
143 ? { status: "unauthenticated" }
144 : { status: "authenticated", label: method };
145}
146
147/**
148 * Reads `fx --version`, `fx status --json` (login and default model) and
149 * `fx models --json`. None of them opens an ACP session, which fx would save.
150 */
151export const checkFxProviderStatus = Effect.fn("checkFxProviderStatus")(function* (
152 settings: FxSettings,
153 environment: NodeJS.ProcessEnv,
154): Effect.fn.Return<ServerProviderDraft, never, ChildProcessSpawner.ChildProcessSpawner> {
155 const checkedAt = DateTime.formatIso(yield* DateTime.now);
156 if (!settings.enabled) {
157 return snapshot(settings, checkedAt, {
158 installed: false,
159 version: null,
160 status: "warning",
161 auth: { status: "unknown" },
162 message: "fx is disabled in T3 Code settings.",
163 });
164 }
165
166 const probeEnvironment = providerProbeEnvironment(environment);
167 const versionResult = yield* runFxCli(settings, ["--version"], probeEnvironment).pipe(
168 Effect.timeoutOption(
169 resolveProviderProbeTimeoutMs("fx", VERSION_PROBE_TIMEOUT_MS, environment),
170 ),
171 Effect.result,
172 );
173 if (Result.isFailure(versionResult) || Option.isNone(versionResult.success)) {
174 const missing = Result.isFailure(versionResult) && isCommandMissingCause(versionResult.failure);
175 return snapshot(settings, checkedAt, {
176 installed: !missing,
177 version: null,
178 status: "error",
179 auth: { status: "unknown" },
180 message: missing ? "fx is not installed or not on PATH." : "Failed to run `fx --version`.",
181 });
182 }
183 const versionOutput = versionResult.success.value;
184 const version = parseCliVersionResult(versionOutput);
185 if (versionOutput.code !== 0) {
186 return snapshot(settings, checkedAt, {
187 installed: true,
188 version,
189 status: "error",
190 auth: { status: "unknown" },
191 message: "fx is installed but failed to run.",
192 });
193 }
194
195 const read = (args: ReadonlyArray<string>) =>
196 runFxCli(settings, args, probeEnvironment).pipe(
197 Effect.timeoutOption(resolveProviderProbeTimeoutMs("fx", AUTH_PROBE_TIMEOUT_MS, environment)),
198 Effect.map(Option.filter((output) => output.code === 0)),
199 Effect.map(Option.map((output) => output.stdout)),
200 Effect.orElseSucceed(() => Option.none<string>()),
201 );
202 const status = Option.flatMap(yield* read(["status", "--json"]), decodeFxStatus);
203 const listed = Option.flatMap(yield* read(["models", "--json"]), decodeFxModels).pipe(
204 Option.map((models) => models.ids.flatMap((id) => nonEmptyTrimmed(id) ?? [])),
205 );
206 const auth = fxAuth(Option.getOrUndefined(status)?.auth);
207 const defaultModel = nonEmptyTrimmed(Option.getOrUndefined(status)?.model);
208 const probe =
209 auth.status === "unauthenticated"
210 ? { status: "error" as const, message: "Run `fx login` to sign in." }
211 : auth.status === "unknown"
212 ? {
213 status: "warning" as const,
214 message: "fx is installed but login state could not be determined.",
215 }
216 : Option.isNone(listed)
217 ? {
218 status: "warning" as const,
219 message: "fx is installed but model listing failed. Model options may be incomplete.",
220 }
221 : { status: "ready" as const };
222 return snapshot(
223 settings,
224 checkedAt,
225 { installed: true, version, auth, ...probe },
226 defaultModel,
227 Option.getOrUndefined(listed),
228 );
229});
230
231/** fx's id for "Default": the alias the snapshot gave it, if `fx status` reported one. */
232export const fxDefaultModelId = (models: ReadonlyArray<ServerProviderModel>) =>
233 models.find((model) => model.slug === FX_DEFAULT_MODEL_SLUG)?.aliases?.[0];