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.ts";
14
15export const DEFAULT_TIMEOUT_MS = 4_000;
16// Auth status checks involve disk/network lookups and can be slow on first run (especially Windows)
17export const AUTH_PROBE_TIMEOUT_MS = 10_000;
18
19export interface CommandResult {
20 readonly stdout: string;
21 readonly stderr: string;
22 readonly code: number;
23}
24
25export interface ProviderProbeResult {
26 readonly installed: boolean;
27 readonly version: string | null;
28 readonly status: Exclude<ServerProviderState, "disabled">;
29 readonly auth: ServerProviderAuth;
30 readonly message?: string;
31}
32
33export interface ServerProviderPresentation {
34 readonly displayName: string;
35 readonly badgeLabel?: string;
36 readonly showInteractionModeToggle?: boolean;
37}
38
39export function nonEmptyTrimmed(value: string | undefined): string | undefined {
40 if (!value) return undefined;
41 const trimmed = value.trim();
42 return trimmed.length > 0 ? trimmed : undefined;
43}
44
45export function isCommandMissingCause(error: Error): boolean {
46 const lower = error.message.toLowerCase();
47 return lower.includes("enoent") || lower.includes("notfound");
48}
49
50export const spawnAndCollect = (binaryPath: string, command: ChildProcess.Command) =>
51 Effect.gen(function* () {
52 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
53 const child = yield* spawner.spawn(command);
54 const [stdout, stderr, exitCode] = yield* Effect.all(
55 [
56 collectStreamAsString(child.stdout),
57 collectStreamAsString(child.stderr),
58 child.exitCode.pipe(Effect.map(Number)),
59 ],
60 { concurrency: "unbounded" },
61 );
62
63 const result: CommandResult = { stdout, stderr, code: exitCode };
64 if (isWindowsCommandNotFound(exitCode, stderr)) {
65 return yield* Effect.fail(new Error(`spawn ${binaryPath} ENOENT`));
66 }
67 return result;
68 }).pipe(Effect.scoped);
69
70export function detailFromResult(
71 result: CommandResult & { readonly timedOut?: boolean },
72): string | undefined {
73 if (result.timedOut) return "Timed out while running command.";
74 const stderr = nonEmptyTrimmed(result.stderr);
75 if (stderr) return stderr;
76 const stdout = nonEmptyTrimmed(result.stdout);
77 if (stdout) return stdout;
78 if (result.code !== 0) {
79 return `Command exited with code ${result.code}.`;
80 }
81 return undefined;
82}
83
84export function extractAuthBoolean(value: unknown): boolean | undefined {
85 if (globalThis.Array.isArray(value)) {
86 for (const entry of value) {
87 const nested = extractAuthBoolean(entry);
88 if (nested !== undefined) return nested;
89 }
90 return undefined;
91 }
92
93 if (!value || typeof value !== "object") return undefined;
94
95 const record = value as Record<string, unknown>;
96 for (const key of ["authenticated", "isAuthenticated", "loggedIn", "isLoggedIn"] as const) {
97 if (typeof record[key] === "boolean") return record[key];
98 }
99 for (const key of ["auth", "status", "session", "account"] as const) {
100 const nested = extractAuthBoolean(record[key]);
101 if (nested !== undefined) return nested;
102 }
103 return undefined;
104}
105
106export function parseGenericCliVersion(output: string): string | null {
107 const match = output.match(/\b(\d+\.\d+\.\d+)\b/);
108 return match?.[1] ?? null;
109}
110
111export function providerModelsFromSettings(
112 builtInModels: ReadonlyArray<ServerProviderModel>,
113 provider: ServerProvider["provider"],
114 customModels: ReadonlyArray<string>,
115 customModelCapabilities: ModelCapabilities,
116): ReadonlyArray<ServerProviderModel> {
117 const resolvedBuiltInModels = [...builtInModels];
118 const seen = new Set(resolvedBuiltInModels.map((model) => model.slug));
119 const customEntries: ServerProviderModel[] = [];
120
121 for (const candidate of customModels) {
122 const normalized = normalizeModelSlug(candidate, provider);
123 if (!normalized || seen.has(normalized)) {
124 continue;
125 }
126 seen.add(normalized);
127 customEntries.push({
128 slug: normalized,
129 name: normalized,
130 isCustom: true,
131 capabilities: customModelCapabilities,
132 });
133 }
134
135 return [...resolvedBuiltInModels, ...customEntries];
136}
137
138export function buildSelectOptionDescriptor(input: {
139 readonly id: string;
140 readonly label: string;
141 readonly options:
142 | ReadonlyArray<{ value: string; label: string; isDefault?: boolean | undefined }>
143 | undefined;
144 readonly description?: string;
145 readonly promptInjectedValues?: ReadonlyArray<string>;
146}) {
147 const options = (input.options ?? []).map((option) =>
148 option.isDefault
149 ? { id: option.value, label: option.label, isDefault: true }
150 : { id: option.value, label: option.label },
151 );
152 const currentValue = options.find((option) => option.isDefault)?.id;
153 return {
154 id: input.id,
155 label: input.label,
156 type: "select" as const,
157 options,
158 ...(currentValue ? { currentValue } : {}),
159 ...(input.description ? { description: input.description } : {}),
160 ...(input.promptInjectedValues && input.promptInjectedValues.length > 0
161 ? { promptInjectedValues: [...input.promptInjectedValues] }
162 : {}),
163 };
164}
165
166export function buildBooleanOptionDescriptor(input: {
167 readonly id: string;
168 readonly label: string;
169 readonly currentValue?: boolean;
170 readonly description?: string;
171}) {
172 return {
173 id: input.id,
174 label: input.label,
175 type: "boolean" as const,
176 ...(input.description ? { description: input.description } : {}),
177 ...(typeof input.currentValue === "boolean" ? { currentValue: input.currentValue } : {}),
178 };
179}
180
181export function buildServerProvider(input: {
182 provider: ServerProvider["provider"];
183 presentation: ServerProviderPresentation;
184 enabled: boolean;
185 checkedAt: string;
186 models: ReadonlyArray<ServerProviderModel>;
187 slashCommands?: ReadonlyArray<ServerProviderSlashCommand>;
188 skills?: ReadonlyArray<ServerProviderSkill>;
189 probe: ProviderProbeResult;
190}): ServerProvider {
191 return {
192 provider: input.provider,
193 displayName: input.presentation.displayName,
194 ...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}),
195 ...(typeof input.presentation.showInteractionModeToggle === "boolean"
196 ? { showInteractionModeToggle: input.presentation.showInteractionModeToggle }
197 : {}),
198 enabled: input.enabled,
199 installed: input.probe.installed,
200 version: input.probe.version,
201 status: input.enabled ? input.probe.status : "disabled",
202 auth: input.probe.auth,
203 checkedAt: input.checkedAt,
204 ...(input.probe.message ? { message: input.probe.message } : {}),
205 models: input.models,
206 slashCommands: [...(input.slashCommands ?? [])],
207 skills: [...(input.skills ?? [])],
208 };
209}
210
211export const collectStreamAsString = <E>(
212 stream: Stream.Stream<Uint8Array, E>,
213): Effect.Effect<string, E> =>
214 stream.pipe(
215 Stream.decodeText(),
216 Stream.runFold(
217 () => "",
218 (acc, chunk) => acc + chunk,
219 ),
220 );