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

providerSnapshot.ts

246 lines8.5 KB

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