Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

status.ts

230 lines7.8 KB

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