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

providerSnapshot.ts

156 lines4.8 KB

1import type {
2 ServerProvider,
3 ServerProviderAuth,
4 ServerProviderModel,
5 ServerProviderState,
6} from "@t3tools/contracts";
7import { Effect, Stream } from "effect";
8import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
9import { normalizeModelSlug } from "@t3tools/shared/model";
10import { isWindowsCommandNotFound } from "../processRunner";
11​
12export const DEFAULT_TIMEOUT_MS = 4_000;
13​
14export interface CommandResult {
15 readonly stdout: string;
16 readonly stderr: string;
17 readonly code: number;
19​
20export interface ProviderProbeResult {
21 readonly installed: boolean;
22 readonly version: string | null;
23 readonly status: Exclude<ServerProviderState, "disabled">;
24 readonly auth: ServerProviderAuth;
25 readonly message?: string;
27​
28export function nonEmptyTrimmed(value: string | undefined): string | undefined {
29 if (!value) return undefined;
30 const trimmed = value.trim();
31 return trimmed.length > 0 ? trimmed : undefined;
33​
34export function isCommandMissingCause(error: unknown): boolean {
35 if (!(error instanceof Error)) return false;
36 const lower = error.message.toLowerCase();
37 return lower.includes("enoent") || lower.includes("notfound");
39​
40export const spawnAndCollect = (binaryPath: string, command: ChildProcess.Command) =>
41 Effect.gen(function* () {
42 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
43 const child = yield* spawner.spawn(command);
44 const [stdout, stderr, exitCode] = yield* Effect.all(
45 [
46 collectStreamAsString(child.stdout),
47 collectStreamAsString(child.stderr),
48 child.exitCode.pipe(Effect.map(Number)),
49 ],
50 { concurrency: "unbounded" },
51 );
52​
53 const result: CommandResult = { stdout, stderr, code: exitCode };
54 if (isWindowsCommandNotFound(exitCode, stderr)) {
55 return yield* Effect.fail(new Error(`spawn ${binaryPath} ENOENT`));
56 }
57 return result;
58 }).pipe(Effect.scoped);
59​
60export function detailFromResult(
61 result: CommandResult & { readonly timedOut?: boolean },
62): string | undefined {
63 if (result.timedOut) return "Timed out while running command.";
64 const stderr = nonEmptyTrimmed(result.stderr);
65 if (stderr) return stderr;
66 const stdout = nonEmptyTrimmed(result.stdout);
67 if (stdout) return stdout;
68 if (result.code !== 0) {
69 return `Command exited with code ${result.code}.`;
70 }
71 return undefined;
73​
74export function extractAuthBoolean(value: unknown): boolean | undefined {
75 if (globalThis.Array.isArray(value)) {
76 for (const entry of value) {
77 const nested = extractAuthBoolean(entry);
78 if (nested !== undefined) return nested;
79 }
80 return undefined;
81 }
82​
83 if (!value || typeof value !== "object") return undefined;
84​
85 const record = value as Record<string, unknown>;
86 for (const key of ["authenticated", "isAuthenticated", "loggedIn", "isLoggedIn"] as const) {
87 if (typeof record[key] === "boolean") return record[key];
88 }
89 for (const key of ["auth", "status", "session", "account"] as const) {
90 const nested = extractAuthBoolean(record[key]);
91 if (nested !== undefined) return nested;
92 }
93 return undefined;
95​
96export function parseGenericCliVersion(output: string): string | null {
97 const match = output.match(/\b(\d+\.\d+\.\d+)\b/);
98 return match?.[1] ?? null;
100​
101export function providerModelsFromSettings(
102 builtInModels: ReadonlyArray<ServerProviderModel>,
103 provider: ServerProvider["provider"],
104 customModels: ReadonlyArray<string>,
105): ReadonlyArray<ServerProviderModel> {
106 const resolvedBuiltInModels = [...builtInModels];
107 const seen = new Set(resolvedBuiltInModels.map((model) => model.slug));
108 const customEntries: ServerProviderModel[] = [];
109​
110 for (const candidate of customModels) {
111 const normalized = normalizeModelSlug(candidate, provider);
112 if (!normalized || seen.has(normalized)) {
113 continue;
114 }
115 seen.add(normalized);
116 customEntries.push({
117 slug: normalized,
118 name: normalized,
119 isCustom: true,
120 capabilities: null,
121 });
122 }
123​
124 return [...resolvedBuiltInModels, ...customEntries];
126​
127export function buildServerProvider(input: {
128 provider: ServerProvider["provider"];
129 enabled: boolean;
130 checkedAt: string;
131 models: ReadonlyArray<ServerProviderModel>;
132 probe: ProviderProbeResult;
133}): ServerProvider {
134 return {
135 provider: input.provider,
136 enabled: input.enabled,
137 installed: input.probe.installed,
138 version: input.probe.version,
139 status: input.enabled ? input.probe.status : "disabled",
140 auth: input.probe.auth,
141 checkedAt: input.checkedAt,
142 ...(input.probe.message ? { message: input.probe.message } : {}),
143 models: input.models,
144 };
146​
147export const collectStreamAsString = <E>(
148 stream: Stream.Stream<Uint8Array, E>,
149): Effect.Effect<string, E> =>
150 stream.pipe(
151 Stream.decodeText(),
152 Stream.runFold(
153 () => "",
154 (acc, chunk) => acc + chunk,
155 ),
156 );