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