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