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

providerSnapshot.ts

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