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

providerSnapshot.ts

245 lines8.4 KB

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