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

snapshotProbe.ts

298 lines10.4 KB

1import type {
2 CustomModelSetting,
3 ProviderDriverKind,
4 ModelCapabilities,
5 RuntimeMode,
6 ServerProvider,
7 ServerProviderAuth,
8 ServerProviderSkill,
9 ServerProviderSlashCommand,
10 ServerProviderModel,
11 ServerProviderUpdateRequiredModel,
12 ServerProviderState,
13 ServerProviderUsageLimits,
14} from "@t3tools/contracts";
15import * as Effect from "effect/Effect";
16import * as PlatformError from "effect/PlatformError";
17import * as Schema from "effect/Schema";
18import * as Stream from "effect/Stream";
19import * as ChildProcess from "effect/process/ChildProcess";
20import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
21import { readCustomModelEntries } from "@t3tools/shared/model";
22import * as HostProcess from "@t3tools/shared/HostProcess";
23import { createProviderVersionAdvisory } from "./maintenanceResolver.ts";
24import { collectUint8StreamText } from "./collectStreamText.ts";
25​
26const WINDOWS_COMMAND_NOT_FOUND_PATTERNS = [
27 /is not recognized as an internal or external command/i,
28 /n.o . reconhecido como um comando interno/i,
29 /non . riconosciuto come comando interno o esterno/i,
30 /n.est pas reconnu en tant que commande interne/i,
31 /no se reconoce como un comando interno o externo/i,
32 /wird nicht als interner oder externer befehl/i,
33] as const;
34​
35export const isWindowsCommandNotFound = Effect.fn("isWindowsCommandNotFound")(function* (
36 code: number | null,
37 stderr: string,
38) {
39 const platform = yield* HostProcess.Platform;
40 if (platform !== "win32") return false;
41 if (code === 9009) return true;
42 return WINDOWS_COMMAND_NOT_FOUND_PATTERNS.some((pattern) => pattern.test(stderr));
43});
44​
45export const DEFAULT_TIMEOUT_MS = 4_000;
46export const AUTH_PROBE_TIMEOUT_MS = 10_000;
47​
48export const COMPACT_SLASH_COMMAND = {
49 name: "compact",
50 description: "Summarize the conversation and reduce context usage",
51} satisfies ServerProviderSlashCommand;
52​
53export interface CommandResult {
54 readonly stdout: string;
55 readonly stderr: string;
56 readonly code: number;
58​
59export class ProviderCommandNotFoundError extends Schema.TaggedError<ProviderCommandNotFoundError>()(
60 "ProviderCommandNotFoundError",
61 {
62 binaryPath: Schema.String,
63 exitCode: Schema.Number,
64 stdoutLength: Schema.Number,
65 stderrLength: Schema.Number,
66 },
67) {
68 override get message(): string {
69 return `Provider command ${this.binaryPath} was not found (exit code ${this.exitCode}).`;
70 }
72​
73const isProviderCommandNotFoundError = Schema.is(ProviderCommandNotFoundError);
74​
75export interface ProviderProbeResult {
76 readonly installed: boolean;
77 readonly version: string | null;
78 readonly status: Exclude<ServerProviderState, "disabled">;
79 readonly auth: ServerProviderAuth;
80 readonly message?: string;
81 readonly usageLimits?: ServerProviderUsageLimits;
83​
84export interface ServerProviderPresentation {
85 readonly displayName: string;
86 readonly badgeLabel?: string;
87 readonly showInteractionModeToggle?: boolean;
88 readonly reportsContextWindow?: boolean;
89 readonly supportedRuntimeModes?: ReadonlyArray<RuntimeMode>;
90 readonly supportsConversationRollback?: boolean;
92​
93export type ServerProviderDraft = Omit<ServerProvider, "instanceId" | "driver">;
94​
95export function nonEmptyTrimmed(value: string | undefined): string | undefined {
96 if (!value) return undefined;
97 const trimmed = value.trim();
98 return trimmed.length > 0 ? trimmed : undefined;
100​
101export function isCommandMissingCause(error: unknown): boolean {
102 if (isProviderCommandNotFoundError(error)) return true;
103 return error instanceof PlatformError.PlatformError && error.reason._tag === "NotFound";
105​
106/**
107 * Environment for background status probes. A mise shim for a missing tool would otherwise
108 * download it on every refresh and leave a partial download behind when the probe times out.
109 * Sessions and user-started commands keep the plain environment, so mise still installs there.
110 */
111export function providerProbeEnvironment(environment: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
112 return { ...environment, MISE_OFFLINE: "1" };
114​
115export const spawnAndCollect = Effect.fn("snapshotProbe.spawnAndCollect")(function* (
116 binaryPath: string,
117 command: ChildProcess.Command,
118) {
119 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
120 const child = yield* spawner.spawn(command);
121 const [stdout, stderr, exitCode] = yield* Effect.all(
122 [
123 collectStreamAsString(child.stdout),
124 collectStreamAsString(child.stderr),
125 child.exitCode.pipe(Effect.map(Number)),
126 ],
127 { concurrency: "unbounded" },
128 );
129​
130 const result: CommandResult = { stdout, stderr, code: exitCode };
131 if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
132 return yield* new ProviderCommandNotFoundError({
133 binaryPath,
134 exitCode,
135 stdoutLength: stdout.length,
136 stderrLength: stderr.length,
137 });
138 }
139 return result;
140}, Effect.scoped);
141​
142export function parseGenericCliVersion(output: string): string | null {
143 // Consume v before the digits; v2 has no internal word boundary.
144 const match = output.match(/\bv?(\d+\.\d+\.\d+)\b/);
145 return match?.[1] ?? null;
147​
148/** A failed `--version` run reports no version: its output can be a wrapper's, such as mise's. */
149export function parseCliVersionResult(
150 result: CommandResult,
151 parse: (output: string) => string | null = parseGenericCliVersion,
152): string | null {
153 return result.code === 0 ? parse(`${result.stdout}\n${result.stderr}`) : null;
155​
156export function providerModelsFromSettings(
157 builtInModels: ReadonlyArray<ServerProviderModel>,
158 customModels: ReadonlyArray<CustomModelSetting>,
159 customModelCapabilities: ModelCapabilities | null,
160): ReadonlyArray<ServerProviderModel> {
161 const entries = readCustomModelEntries(customModels);
162 if (entries.length === 0) return builtInModels;
163​
164 const nameOverrides = new Map(
165 entries.filter((entry) => entry.name !== entry.slug).map((entry) => [entry.slug, entry.name]),
166 );
167 const resolvedBuiltInModels = builtInModels.map((model) => {
168 const name = nameOverrides.get(model.slug);
169 if (!name) return model;
170 const { shortName: _shortName, ...rest } = model;
171 return { ...rest, name };
172 });
173 const seen = new Set(resolvedBuiltInModels.map((model) => model.slug));
174 const customEntries: ServerProviderModel[] = [];
175​
176 for (const entry of entries) {
177 if (seen.has(entry.slug)) {
178 continue;
179 }
180 seen.add(entry.slug);
181 customEntries.push({
182 slug: entry.slug,
183 name: entry.name,
184 isCustom: true,
185 capabilities: entry.capabilities ?? customModelCapabilities,
186 });
187 }
188​
189 return [...resolvedBuiltInModels, ...customEntries];
191​
192export function buildSelectOptionDescriptor(input: {
193 readonly id: string;
194 readonly label: string;
195 readonly options:
196 | ReadonlyArray<{
197 value: string;
198 label: string;
199 description?: string | undefined;
200 isDefault?: boolean | undefined;
201 }>
202 | undefined;
203 readonly description?: string;
204 readonly promptInjectedValues?: ReadonlyArray<string>;
205}) {
206 const options = (input.options ?? []).map((option) => ({
207 id: option.value,
208 label: option.label,
209 ...(option.description ? { description: option.description } : {}),
210 ...(option.isDefault ? { isDefault: true } : {}),
211 }));
212 const currentValue = options.find((option) => option.isDefault)?.id;
213 return {
214 id: input.id,
215 label: input.label,
216 type: "select" as const,
217 options,
218 ...(currentValue ? { currentValue } : {}),
219 ...(input.description ? { description: input.description } : {}),
220 ...(input.promptInjectedValues && input.promptInjectedValues.length > 0
221 ? { promptInjectedValues: [...input.promptInjectedValues] }
222 : {}),
223 };
225​
226export function buildBooleanOptionDescriptor(input: {
227 readonly id: string;
228 readonly label: string;
229 readonly currentValue?: boolean;
230 readonly description?: string;
231}) {
232 return {
233 id: input.id,
234 label: input.label,
235 type: "boolean" as const,
236 ...(input.description ? { description: input.description } : {}),
237 ...(typeof input.currentValue === "boolean" ? { currentValue: input.currentValue } : {}),
238 };
240​
241export function buildServerProvider(input: {
242 driver?: ProviderDriverKind;
243 presentation: ServerProviderPresentation;
244 enabled: boolean;
245 checkedAt: string;
246 models: ReadonlyArray<ServerProviderModel>;
247 updateRequiredModels?: ReadonlyArray<ServerProviderUpdateRequiredModel>;
248 slashCommands?: ReadonlyArray<ServerProviderSlashCommand>;
249 skills?: ReadonlyArray<ServerProviderSkill>;
250 probe: ProviderProbeResult;
251}): ServerProviderDraft {
252 const versionAdvisory = input.driver
253 ? createProviderVersionAdvisory({
254 driver: input.driver,
255 currentVersion: input.probe.version,
256 checkedAt: input.checkedAt,
257 })
258 : undefined;
259 return {
260 displayName: input.presentation.displayName,
261 ...(typeof input.presentation.supportsConversationRollback === "boolean"
262 ? { supportsConversationRollback: input.presentation.supportsConversationRollback }
263 : {}),
264 ...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}),
265 ...(typeof input.presentation.showInteractionModeToggle === "boolean"
266 ? { showInteractionModeToggle: input.presentation.showInteractionModeToggle }
267 : {}),
268 ...(typeof input.presentation.reportsContextWindow === "boolean"
269 ? { reportsContextWindow: input.presentation.reportsContextWindow }
270 : {}),
271 ...(input.presentation.supportedRuntimeModes === undefined
272 ? {}
273 : { supportedRuntimeModes: [...input.presentation.supportedRuntimeModes] }),
274 enabled: input.enabled,
275 installed: input.probe.installed,
276 version: input.probe.version,
277 status: input.enabled ? input.probe.status : "disabled",
278 auth: input.probe.auth,
279 // Drivers with in-app setup replace these CLI-owned defaults.
280 setup: { canAuthenticate: false, canInstall: false },
281 checkedAt: input.checkedAt,
282 ...(input.probe.message ? { message: input.probe.message } : {}),
283 models: input.models,
284 ...(input.updateRequiredModels?.length
285 ? { updateRequiredModels: input.updateRequiredModels }
286 : {}),
287 slashCommands: [...(input.slashCommands ?? [])],
288 skills: [...(input.skills ?? [])],
289 ...(input.probe.usageLimits ? { usageLimits: input.probe.usageLimits } : {}),
290 ...(versionAdvisory ? { versionAdvisory } : {}),
291 };
293​
294export const collectStreamAsString = <E>(
295 stream: Stream.Stream<Uint8Array, E>,
296 options?: { readonly maxBytes?: number | undefined },
297): Effect.Effect<string, E> =>
298 collectUint8StreamText({ stream, ...options }).pipe(Effect.map((collected) => collected.text));