Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

providerSnapshot.ts

259 lines8.6 KB

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 { normalizeCustomModelSlug } 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;
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 }
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;
54​
55export interface ServerProviderPresentation {
56 readonly displayName: string;
57 readonly badgeLabel?: string;
58 readonly showInteractionModeToggle?: boolean;
59 readonly requiresNewThreadForModelChange?: boolean;
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;
69​
70export function isCommandMissingCause(error: unknown): boolean {
71 if (isProviderCommandNotFoundError(error)) return true;
72 return error instanceof PlatformError.PlatformError && error.reason._tag === "NotFound";
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;
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;
135​
136export function parseGenericCliVersion(output: string): string | null {
137 const match = output.match(/\b(\d+\.\d+\.\d+)\b/);
138 return match?.[1] ?? null;
140​
141export function providerModelsFromSettings(
142 builtInModels: ReadonlyArray<ServerProviderModel>,
143 customModels: ReadonlyArray<string>,
144 customModelCapabilities: ModelCapabilities,
145): ReadonlyArray<ServerProviderModel> {
146 const resolvedBuiltInModels = [...builtInModels];
147 const seen = new Set(resolvedBuiltInModels.map((model) => model.slug));
148 const customEntries: ServerProviderModel[] = [];
149​
150 for (const candidate of customModels) {
151 const normalized = normalizeCustomModelSlug(candidate);
152 if (!normalized || seen.has(normalized)) {
153 continue;
154 }
155 seen.add(normalized);
156 customEntries.push({
157 slug: normalized,
158 name: normalized,
159 isCustom: true,
160 capabilities: customModelCapabilities,
161 });
162 }
163​
164 return [...resolvedBuiltInModels, ...customEntries];
166​
167export function buildSelectOptionDescriptor(input: {
168 readonly id: string;
169 readonly label: string;
170 readonly options:
171 | ReadonlyArray<{
172 value: string;
173 label: string;
174 description?: string | undefined;
175 isDefault?: boolean | undefined;
176 }>
177 | undefined;
178 readonly description?: string;
179 readonly promptInjectedValues?: ReadonlyArray<string>;
180}) {
181 const options = (input.options ?? []).map((option) => ({
182 id: option.value,
183 label: option.label,
184 ...(option.description ? { description: option.description } : {}),
185 ...(option.isDefault ? { isDefault: true } : {}),
186 }));
187 const currentValue = options.find((option) => option.isDefault)?.id;
188 return {
189 id: input.id,
190 label: input.label,
191 type: "select" as const,
192 options,
193 ...(currentValue ? { currentValue } : {}),
194 ...(input.description ? { description: input.description } : {}),
195 ...(input.promptInjectedValues && input.promptInjectedValues.length > 0
196 ? { promptInjectedValues: [...input.promptInjectedValues] }
197 : {}),
198 };
200​
201export function buildBooleanOptionDescriptor(input: {
202 readonly id: string;
203 readonly label: string;
204 readonly currentValue?: boolean;
205 readonly description?: string;
206}) {
207 return {
208 id: input.id,
209 label: input.label,
210 type: "boolean" as const,
211 ...(input.description ? { description: input.description } : {}),
212 ...(typeof input.currentValue === "boolean" ? { currentValue: input.currentValue } : {}),
213 };
215​
216export function buildServerProvider(input: {
217 driver?: ProviderDriverKind;
218 presentation: ServerProviderPresentation;
219 enabled: boolean;
220 checkedAt: string;
221 models: ReadonlyArray<ServerProviderModel>;
222 slashCommands?: ReadonlyArray<ServerProviderSlashCommand>;
223 skills?: ReadonlyArray<ServerProviderSkill>;
224 probe: ProviderProbeResult;
225}): ServerProviderDraft {
226 const versionAdvisory = input.driver
227 ? createProviderVersionAdvisory({
228 driver: input.driver,
229 currentVersion: input.probe.version,
230 checkedAt: input.checkedAt,
231 })
232 : undefined;
233 return {
234 displayName: input.presentation.displayName,
235 ...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}),
236 ...(typeof input.presentation.showInteractionModeToggle === "boolean"
237 ? { showInteractionModeToggle: input.presentation.showInteractionModeToggle }
238 : {}),
239 ...(typeof input.presentation.requiresNewThreadForModelChange === "boolean"
240 ? { requiresNewThreadForModelChange: input.presentation.requiresNewThreadForModelChange }
241 : {}),
242 enabled: input.enabled,
243 installed: input.probe.installed,
244 version: input.probe.version,
245 status: input.enabled ? input.probe.status : "disabled",
246 auth: input.probe.auth,
247 checkedAt: input.checkedAt,
248 ...(input.probe.message ? { message: input.probe.message } : {}),
249 models: input.models,
250 slashCommands: [...(input.slashCommands ?? [])],
251 skills: [...(input.skills ?? [])],
252 ...(versionAdvisory ? { versionAdvisory } : {}),
253 };
255​
256export const collectStreamAsString = <E>(
257 stream: Stream.Stream<Uint8Array, E>,
258): Effect.Effect<string, E> =>
259 collectUint8StreamText({ stream }).pipe(Effect.map((collected) => collected.text));