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

providerSnapshot.ts

268 lines9.0 KB

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