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