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

providerSnapshot.ts

158 lines4.9 KB

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