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

status.ts

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