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