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

providerSnapshot.ts

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