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