Open History to see the last commit
1import type {
2 CustomModelSetting,
3 ProviderDriverKind,
4 ModelCapabilities,
5 RuntimeMode,
6 ServerProvider,
7 ServerProviderAuth,
8 ServerProviderSkill,
9 ServerProviderSlashCommand,
10 ServerProviderModel,
11 ServerProviderUpdateRequiredModel,
12 ServerProviderState,
13 ServerProviderUsageLimits,
14} from "@t3tools/contracts";
15import * as Effect from "effect/Effect";
16import * as PlatformError from "effect/PlatformError";
17import * as Schema from "effect/Schema";
18import * as Stream from "effect/Stream";
19import * as ChildProcess from "effect/process/ChildProcess";
20import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
21import { readCustomModelEntries } from "@t3tools/shared/model";
22import * as HostProcess from "@t3tools/shared/HostProcess";
23import { createProviderVersionAdvisory } from "./maintenanceResolver.ts";
24import { collectUint8StreamText } from "./collectStreamText.ts";
25
26const WINDOWS_COMMAND_NOT_FOUND_PATTERNS = [
27 /is not recognized as an internal or external command/i,
28 /n.o . reconhecido como um comando interno/i,
29 /non . riconosciuto come comando interno o esterno/i,
30 /n.est pas reconnu en tant que commande interne/i,
31 /no se reconoce como un comando interno o externo/i,
32 /wird nicht als interner oder externer befehl/i,
33] as const;
34
35export const isWindowsCommandNotFound = Effect.fn("isWindowsCommandNotFound")(function* (
36 code: number | null,
37 stderr: string,
38) {
39 const platform = yield* HostProcess.Platform;
40 if (platform !== "win32") return false;
41 if (code === 9009) return true;
42 return WINDOWS_COMMAND_NOT_FOUND_PATTERNS.some((pattern) => pattern.test(stderr));
43});
44
45export const DEFAULT_TIMEOUT_MS = 4_000;
46export const AUTH_PROBE_TIMEOUT_MS = 10_000;
47
48export const COMPACT_SLASH_COMMAND = {
49 name: "compact",
50 description: "Summarize the conversation and reduce context usage",
51} satisfies ServerProviderSlashCommand;
52
53export interface CommandResult {
54 readonly stdout: string;
55 readonly stderr: string;
56 readonly code: number;
57}
58
59export class ProviderCommandNotFoundError extends Schema.TaggedError<ProviderCommandNotFoundError>()(
60 "ProviderCommandNotFoundError",
61 {
62 binaryPath: Schema.String,
63 exitCode: Schema.Number,
64 stdoutLength: Schema.Number,
65 stderrLength: Schema.Number,
66 },
67) {
68 override get message(): string {
69 return `Provider command ${this.binaryPath} was not found (exit code ${this.exitCode}).`;
70 }
71}
72
73const isProviderCommandNotFoundError = Schema.is(ProviderCommandNotFoundError);
74
75export interface ProviderProbeResult {
76 readonly installed: boolean;
77 readonly version: string | null;
78 readonly status: Exclude<ServerProviderState, "disabled">;
79 readonly auth: ServerProviderAuth;
80 readonly message?: string;
81 readonly usageLimits?: ServerProviderUsageLimits;
82}
83
84export interface ServerProviderPresentation {
85 readonly displayName: string;
86 readonly badgeLabel?: string;
87 readonly showInteractionModeToggle?: boolean;
88 readonly reportsContextWindow?: boolean;
89 readonly supportedRuntimeModes?: ReadonlyArray<RuntimeMode>;
90 readonly requiresNewThreadForModelChange?: boolean;
91 readonly supportsConversationRollback?: boolean;
92}
93
94export type ServerProviderDraft = Omit<ServerProvider, "instanceId" | "driver">;
95
96export function nonEmptyTrimmed(value: string | undefined): string | undefined {
97 if (!value) return undefined;
98 const trimmed = value.trim();
99 return trimmed.length > 0 ? trimmed : undefined;
100}
101
102export function isCommandMissingCause(error: unknown): boolean {
103 if (isProviderCommandNotFoundError(error)) return true;
104 return error instanceof PlatformError.PlatformError && error.reason._tag === "NotFound";
105}
106
107export const spawnAndCollect = Effect.fn("snapshotProbe.spawnAndCollect")(function* (
108 binaryPath: string,
109 command: ChildProcess.Command,
110) {
111 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
112 const child = yield* spawner.spawn(command);
113 const [stdout, stderr, exitCode] = yield* Effect.all(
114 [
115 collectStreamAsString(child.stdout),
116 collectStreamAsString(child.stderr),
117 child.exitCode.pipe(Effect.map(Number)),
118 ],
119 { concurrency: "unbounded" },
120 );
121
122 const result: CommandResult = { stdout, stderr, code: exitCode };
123 if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
124 return yield* new ProviderCommandNotFoundError({
125 binaryPath,
126 exitCode,
127 stdoutLength: stdout.length,
128 stderrLength: stderr.length,
129 });
130 }
131 return result;
132}, Effect.scoped);
133
134export function parseGenericCliVersion(output: string): string | null {
135 // Consume v before the digits; v2 has no internal word boundary.
136 const match = output.match(/\bv?(\d+\.\d+\.\d+)\b/);
137 return match?.[1] ?? null;
138}
139
140export function providerModelsFromSettings(
141 builtInModels: ReadonlyArray<ServerProviderModel>,
142 customModels: ReadonlyArray<CustomModelSetting>,
143 customModelCapabilities: ModelCapabilities | null,
144): ReadonlyArray<ServerProviderModel> {
145 const entries = readCustomModelEntries(customModels);
146 if (entries.length === 0) return builtInModels;
147
148 const nameOverrides = new Map(
149 entries.filter((entry) => entry.name !== entry.slug).map((entry) => [entry.slug, entry.name]),
150 );
151 const resolvedBuiltInModels = builtInModels.map((model) => {
152 const name = nameOverrides.get(model.slug);
153 if (!name) return model;
154 const { shortName: _shortName, ...rest } = model;
155 return { ...rest, name };
156 });
157 const seen = new Set(resolvedBuiltInModels.map((model) => model.slug));
158 const customEntries: ServerProviderModel[] = [];
159
160 for (const entry of entries) {
161 if (seen.has(entry.slug)) {
162 continue;
163 }
164 seen.add(entry.slug);
165 customEntries.push({
166 slug: entry.slug,
167 name: entry.name,
168 isCustom: true,
169 capabilities: entry.capabilities ?? customModelCapabilities,
170 });
171 }
172
173 return [...resolvedBuiltInModels, ...customEntries];
174}
175
176export function buildSelectOptionDescriptor(input: {
177 readonly id: string;
178 readonly label: string;
179 readonly options:
180 | ReadonlyArray<{
181 value: string;
182 label: string;
183 description?: string | undefined;
184 isDefault?: boolean | undefined;
185 }>
186 | undefined;
187 readonly description?: string;
188 readonly promptInjectedValues?: ReadonlyArray<string>;
189}) {
190 const options = (input.options ?? []).map((option) => ({
191 id: option.value,
192 label: option.label,
193 ...(option.description ? { description: option.description } : {}),
194 ...(option.isDefault ? { isDefault: true } : {}),
195 }));
196 const currentValue = options.find((option) => option.isDefault)?.id;
197 return {
198 id: input.id,
199 label: input.label,
200 type: "select" as const,
201 options,
202 ...(currentValue ? { currentValue } : {}),
203 ...(input.description ? { description: input.description } : {}),
204 ...(input.promptInjectedValues && input.promptInjectedValues.length > 0
205 ? { promptInjectedValues: [...input.promptInjectedValues] }
206 : {}),
207 };
208}
209
210export function buildBooleanOptionDescriptor(input: {
211 readonly id: string;
212 readonly label: string;
213 readonly currentValue?: boolean;
214 readonly description?: string;
215}) {
216 return {
217 id: input.id,
218 label: input.label,
219 type: "boolean" as const,
220 ...(input.description ? { description: input.description } : {}),
221 ...(typeof input.currentValue === "boolean" ? { currentValue: input.currentValue } : {}),
222 };
223}
224
225export function buildServerProvider(input: {
226 driver?: ProviderDriverKind;
227 presentation: ServerProviderPresentation;
228 enabled: boolean;
229 checkedAt: string;
230 models: ReadonlyArray<ServerProviderModel>;
231 updateRequiredModels?: ReadonlyArray<ServerProviderUpdateRequiredModel>;
232 slashCommands?: ReadonlyArray<ServerProviderSlashCommand>;
233 skills?: ReadonlyArray<ServerProviderSkill>;
234 probe: ProviderProbeResult;
235}): ServerProviderDraft {
236 const versionAdvisory = input.driver
237 ? createProviderVersionAdvisory({
238 driver: input.driver,
239 currentVersion: input.probe.version,
240 checkedAt: input.checkedAt,
241 })
242 : undefined;
243 return {
244 displayName: input.presentation.displayName,
245 ...(typeof input.presentation.supportsConversationRollback === "boolean"
246 ? { supportsConversationRollback: input.presentation.supportsConversationRollback }
247 : {}),
248 ...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}),
249 ...(typeof input.presentation.showInteractionModeToggle === "boolean"
250 ? { showInteractionModeToggle: input.presentation.showInteractionModeToggle }
251 : {}),
252 ...(typeof input.presentation.reportsContextWindow === "boolean"
253 ? { reportsContextWindow: input.presentation.reportsContextWindow }
254 : {}),
255 ...(input.presentation.supportedRuntimeModes === undefined
256 ? {}
257 : { supportedRuntimeModes: [...input.presentation.supportedRuntimeModes] }),
258 ...(typeof input.presentation.requiresNewThreadForModelChange === "boolean"
259 ? { requiresNewThreadForModelChange: input.presentation.requiresNewThreadForModelChange }
260 : {}),
261 enabled: input.enabled,
262 installed: input.probe.installed,
263 version: input.probe.version,
264 status: input.enabled ? input.probe.status : "disabled",
265 auth: input.probe.auth,
266 // Drivers with in-app setup replace these CLI-owned defaults.
267 setup: { canAuthenticate: false, canInstall: false },
268 checkedAt: input.checkedAt,
269 ...(input.probe.message ? { message: input.probe.message } : {}),
270 models: input.models,
271 ...(input.updateRequiredModels?.length
272 ? { updateRequiredModels: input.updateRequiredModels }
273 : {}),
274 slashCommands: [...(input.slashCommands ?? [])],
275 skills: [...(input.skills ?? [])],
276 ...(input.probe.usageLimits ? { usageLimits: input.probe.usageLimits } : {}),
277 ...(versionAdvisory ? { versionAdvisory } : {}),
278 };
279}
280
281export const collectStreamAsString = <E>(
282 stream: Stream.Stream<Uint8Array, E>,
283 options?: { readonly maxBytes?: number | undefined },
284): Effect.Effect<string, E> =>
285 collectUint8StreamText({ stream, ...options }).pipe(Effect.map((collected) => collected.text));