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.TaggedError<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
70export type ServerProviderDraft = Omit<ServerProvider, "instanceId" | "driver">;
71
72export function nonEmptyTrimmed(value: string | undefined): string | undefined {
73 if (!value) return undefined;
74 const trimmed = value.trim();
75 return trimmed.length > 0 ? trimmed : undefined;
76}
77
78export function isCommandMissingCause(error: unknown): boolean {
79 if (isProviderCommandNotFoundError(error)) return true;
80 return error instanceof PlatformError.PlatformError && error.reason._tag === "NotFound";
81}
82
83export const spawnAndCollect = (binaryPath: string, command: ChildProcess.Command) =>
84 Effect.gen(function* () {
85 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
86 const child = yield* spawner.spawn(command);
87 const [stdout, stderr, exitCode] = yield* Effect.all(
88 [
89 collectStreamAsString(child.stdout),
90 collectStreamAsString(child.stderr),
91 child.exitCode.pipe(Effect.map(Number)),
92 ],
93 { concurrency: "unbounded" },
94 );
95
96 const result: CommandResult = { stdout, stderr, code: exitCode };
97 if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
98 return yield* new ProviderCommandNotFoundError({
99 binaryPath,
100 exitCode,
101 stdoutLength: stdout.length,
102 stderrLength: stderr.length,
103 });
104 }
105 return result;
106 }).pipe(Effect.scoped);
107
108export function parseGenericCliVersion(output: string): string | null {
109 const match = output.match(/\b(\d+\.\d+\.\d+)\b/);
110 return match?.[1] ?? null;
111}
112
113/**
114 * Append the user's custom models after the built-ins. A custom entry that
115 * declares its own capabilities keeps them; a bare slug gets the driver's
116 * default set. Slugs that collide with a built-in are dropped.
117 */
118export function providerModelsFromSettings(
119 builtInModels: ReadonlyArray<ServerProviderModel>,
120 customModels: ReadonlyArray<CustomModelSetting>,
121 customModelCapabilities: ModelCapabilities,
122): ReadonlyArray<ServerProviderModel> {
123 const resolvedBuiltInModels = [...builtInModels];
124 const seen = new Set(resolvedBuiltInModels.map((model) => model.slug));
125 const customEntries: ServerProviderModel[] = [];
126
127 for (const entry of readCustomModelEntries(customModels)) {
128 if (seen.has(entry.slug)) {
129 continue;
130 }
131 seen.add(entry.slug);
132 customEntries.push({
133 slug: entry.slug,
134 name: entry.name,
135 isCustom: true,
136 capabilities: entry.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<{
148 value: string;
149 label: string;
150 description?: string | undefined;
151 isDefault?: boolean | undefined;
152 }>
153 | undefined;
154 readonly description?: string;
155 readonly promptInjectedValues?: ReadonlyArray<string>;
156}) {
157 const options = (input.options ?? []).map((option) => ({
158 id: option.value,
159 label: option.label,
160 ...(option.description ? { description: option.description } : {}),
161 ...(option.isDefault ? { isDefault: true } : {}),
162 }));
163 const currentValue = options.find((option) => option.isDefault)?.id;
164 return {
165 id: input.id,
166 label: input.label,
167 type: "select" as const,
168 options,
169 ...(currentValue ? { currentValue } : {}),
170 ...(input.description ? { description: input.description } : {}),
171 ...(input.promptInjectedValues && input.promptInjectedValues.length > 0
172 ? { promptInjectedValues: [...input.promptInjectedValues] }
173 : {}),
174 };
175}
176
177export function buildBooleanOptionDescriptor(input: {
178 readonly id: string;
179 readonly label: string;
180 readonly currentValue?: boolean;
181 readonly description?: string;
182}) {
183 return {
184 id: input.id,
185 label: input.label,
186 type: "boolean" as const,
187 ...(input.description ? { description: input.description } : {}),
188 ...(typeof input.currentValue === "boolean" ? { currentValue: input.currentValue } : {}),
189 };
190}
191
192export function buildServerProvider(input: {
193 driver?: ProviderDriverKind;
194 presentation: ServerProviderPresentation;
195 enabled: boolean;
196 checkedAt: string;
197 models: ReadonlyArray<ServerProviderModel>;
198 slashCommands?: ReadonlyArray<ServerProviderSlashCommand>;
199 skills?: ReadonlyArray<ServerProviderSkill>;
200 probe: ProviderProbeResult;
201}): ServerProviderDraft {
202 const versionAdvisory = input.driver
203 ? createProviderVersionAdvisory({
204 driver: input.driver,
205 currentVersion: input.probe.version,
206 checkedAt: input.checkedAt,
207 })
208 : undefined;
209 return {
210 displayName: input.presentation.displayName,
211 ...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}),
212 ...(typeof input.presentation.showInteractionModeToggle === "boolean"
213 ? { showInteractionModeToggle: input.presentation.showInteractionModeToggle }
214 : {}),
215 ...(typeof input.presentation.requiresNewThreadForModelChange === "boolean"
216 ? { requiresNewThreadForModelChange: input.presentation.requiresNewThreadForModelChange }
217 : {}),
218 enabled: input.enabled,
219 installed: input.probe.installed,
220 version: input.probe.version,
221 status: input.enabled ? input.probe.status : "disabled",
222 auth: input.probe.auth,
223 checkedAt: input.checkedAt,
224 ...(input.probe.message ? { message: input.probe.message } : {}),
225 models: input.models,
226 slashCommands: [...(input.slashCommands ?? [])],
227 skills: [...(input.skills ?? [])],
228 ...(input.probe.usageLimits ? { usageLimits: input.probe.usageLimits } : {}),
229 ...(versionAdvisory ? { versionAdvisory } : {}),
230 };
231}
232
233export const collectStreamAsString = <E>(
234 stream: Stream.Stream<Uint8Array, E>,
235 options?: { readonly maxBytes?: number | undefined },
236): Effect.Effect<string, E> =>
237 collectUint8StreamText({ stream, ...options }).pipe(Effect.map((collected) => collected.text));